Tag Archives: Rants

Why does Control.Parent exist?

Encapsulation is one of the major tenets of object orient programming. The ability to not worry about how things work behind the scenes and just use a component is lovely.

Recently, I’ve had to be a on a project where a lot of UserControls have been created and tons of them reference their parent property internally to get some bit of data that they need for this or that.

First of all, not only have you completely broken encapsulation by doing that, but now you can’t use that UserControl on any other form.

My favorite part of encapsulation is easy refactoring.  We all make mistakes and wish we would have written something differently, and if we have the time to correct those mistakes we should.  Recently, a developer wanted to give the UI a bit more user-friendliness so he threw a bunch of splitter panels on a form with some grids and UserControls to let the user customize the form a bit.

The problem is one of the UserControls referenced it’s Parent property.  So now instead of ((parentForm)this.Parent).SomeProp I had to go back and fix the bug he introduced by doing this ((parentForm)this.Parent.Parent.Parent.Parent.Parent).SomeProp just get it to run.  I realize shortcuts can save a ton of time in some cases, but why is Control.Parent allowed to exists when it makes it so easy to break encapsulation and lead to big problems with refactoring down the road.