Thursday, December 3, 2009

Posted question on StackOverflow about always subclassing controls -- a la PowerBuilder

In my pre-ASP.NET development environment, there was a near-universal best practice:

* NEVER use the native controls!
* Instead, subclass ALL the controls, and ALWAYS use the subclassed version.

Why? Because that gave you a hook... one place to write code and have it applied throughout your application.

For example: Suppose you decide that you want a question mark icon to appear to the right of every TextBox in your webforms app. The icon is rendered, and hovering over it pops up bubble help -- iff there is text in the TextBox.ToolTip property.

How would you accomplish that, if you're using the MS-provided TextBox control?

If you consistently used a subclassed version of TextBox in your application, then you could go to that object, and add the method that renders the icon, stocked with your favorite bubblehelp javascript.

Presto! All of your app's TextBoxes sprout little question mark icons -- or they will, when you set their ToolTip text.

Over time, you can easily adapt and enhance ALL your TextBoxes, because they all have a base class that you can modify. You add a feature where ToolTips are set from a resource file. Next, you add a ShowOnLeft property that presents the icon on the left side of the TextBox. Do you like how the iPhone password control shows the last character you type, obscuring the earlier characters? Override your subclassed TextBox's default behavior for passwords with a method to implement that behavior.

I have never encountered advocates for this practice, in ASP.NET. Have I just missed it? An article describing two dozen ASP.NET design patterns doesn't have anything related. The posts about *how* to subclass server controls describe special-purpose one-offs, like a TextBox that only accepts digits -- but none of them recommend the pervasive "ALWAYS use subclassed controls!" policy that I subscribed to in olden days.

Does it make sense, to apply this ancient wisdom, when working in ASP.NET? To always use the subclassed equivalent of the native server controls?

If not -- why not? Are there other ways to skin this cat? A technique that provides you with just one place where you can augment ALL your application's instances of a given control?

I'd love to hear about that. I *want* my TextBoxQMark control. :-)

TIA - Hoytster

No comments:

Post a Comment