Saturday, December 20, 2008

Why is CreateHandle protected?

In WinForms, there is a method on Form called CreateHandle that is protected. The method simply forces the Form to create a handle. An exception is thrown if you attempt to modify the form before a handle is created.

In most cases calling CreateHandle is not necessary. When you open the Form, a handle is created automatically. However there are times when I want to modify the Form before the user opens it. To do this I have a couple of choices. I can inherit from Form and expose CreateHandle in a new base class. I can individually expose CreateHandle in every Form for which I want to have this ability. My last choice is to use reflection to gain access to the protected method. Some people will mention that you can simply query the Handle property and that will create a handle. This is not quite true, when using this technique a handle is not created for children of the parent Form:

http://msdn.microsoft.com/en-us/library/system.windows.forms.control.createcontrol.aspx

I do not like any of these options. In fact this is an example of why I do not think protected is a valid level of encapsulation at all. If the functionality is useful, make it public. If it breaks encapsulation, then make it private. Protected is an annoyance that sort of sits between encapsulated and not. Why favor inheritance, a technique that is usually inappropriate and brittle, when composition would be a better choice. The use of the protected keyword pushes me towards inheritance as a design choice even though it is inferior.

If I were to design an object-oriented language, I wouldn't include the protected level of encapsulation.

0 comments:

Post a Comment