Here, I’ll present a simple example of the same control using the rendered method and the composite method. For those new to custom web controls, a rendered control is a class inherited from “Control” or “WebControl” that overrides the “Render” method in order to sned custom markup to the browser. A composite control uses other controls in a hierarchy and leaves the rendering to each control.
Here is a simple rendered control:
6 public class RenderedControl : Control
8 protected override void Render(HtmlTextWriter writer)
10 writer.AddAttribute(HtmlTextWriterAttribute.Id, “myID”);
12 writer.AddAttribute(HtmlTextWriterAttribute.Id, “innerID”);
14 writer.Write(“This text is the meat of this control.”);
It’s pretty straight-forward, and the output will always be this:
18 <div id=”myID”>
19 <span id=”innerID”>This text is the meat of this control.</span>
Here is the same thing using the composite method:
6 public class CompositeControl : Panel
8 protected override void CreateChildControls()
10 base.CreateChildControls ();
12 this.ID = “myID”;
13 Label lbl = new Label();
14 lbl.ID = “innerID”;
15 lbl.Text = “This text is the meat of this control.”;
With the composite method, the developer doesn’t have to worry about the low level markup being rendered, and he can depend on the richer object-oriented contract of each child control. With this method, the developer overrides the CreateChildControls() method and adds child controls. All these child controls will render themselves. The exact same markup renders.
In my opinion, using the composite control method optimizes development time, and that is the most expensive more often than not. I don’t give weight to the performance argument because the difference in performance is on the millisecond scale. The moment you call out-of-process to a database or the file system, you accept a performance hit of much more magnitude; therefore, the performance difference of these two methods is negligible. The composite control method is more maintainable, and maintenance of an application always costs more.