Sunday, August 2, 2009

The Advantages of User Controls

A practice I see used entirely too infrequently is the use of User Controls on webforms. User Controls provide some really great functionality to the ASP.NET programmer, and I think it's a real shame that they're so under-utilized.

The most obvious advantage of a User Control is that it provides a great deal of reusability. Once you've created the User Control, you're free to drop it on any webform or User Control that you want and instantly gain the functionality provided by the User Control. The more broadly-used the User Control becomes, the more you'll be able to tweak the User Control itself to provide really great functionality to consuming webforms. As you continue to develop User Control, you'll gain the ability to correctly predict what will and won't be useful properties and methods. This enhances your ability to provide robust controls with a minimum development/testing cycle.

Another great advantage of User Controls is the abstraction they provide. A User Control allows the programmer to create a self-contained, self-aware (but not in the evil robot way) set of controls that know how to receive a business object, bind the object to its controls, then rehydrate that business object from the controls for later retrieval from the parent form. The parent form is free to do whatever it wants with the rehydrated object, of course, including persistence in the data store.

That is of course a conceptual abstraction. User Controls also offer literal abstraction in that all the UI logic for the User Control is contained within the User Control itself. This removes several chunks of code from the parent form, thereby making it cleaner and easier to debug. As I said in my previous post, I really dislike big, ugly, complex webforms. With User Controls, there really is no need for webforms with overly complex and often very long code besides classes.

My next post will have some general tips when developing User Controls that I've found really make them useful.