Advocates of private/internal modifiers – please proceed to hell

In the past, I often wrote and spoke about the dangers of the C# private/internal/protected modifiers. Today, I’ve stumbled upon yet another case.

In Silverlight, UI controls have a property DataContext, which roughly corresponds to a model property in Smalltalk’s View classes. You set whatever you want to it, and then you can bind its properties to your UI parts using the {Binding} syntax in XAML.

Now imagine the situation, when the {Binding} is not sufficient. For example, you want to handle some error situations. “Piece of cake”, you may think, “I just write a handler to the DataContextChanged event”.

Nope. It is internal. According to Allen Chen, it is internal by design (http://silverlight.net/forums/t/13421.aspx). How in the world a developer at Microsoft can know if I need to access something or not!? Does he knows anything about my requirements, my customer, my architecture? So why does he think he is allowed to decide that?

Please, please, please do consider the following: use access restrictions very sparingly. You don’t know everything about how your code will be used in the future. If you’re concerned about a too large API surface, make the member protected – I could live with that, albeit I do believe that in this particular case such an important property deserves a better visibility. If you believe DataContext concept has to be replaced with some other architecture in the future – well, communicate it NOW and mark the DataContext property with the ObsoleteAttribute. But don’t hide a member just because you cannot think of any good usage. And don’t hide a member because you’re afraid it can be abused.

Ahem.

Okay.

There is a possibility for a change: you can vote here (please, really do!) and wait. If you’re really lucky, they integrate it in Silverlight 4, so it is only a couple of years you have to wait.

And, there  are two workarounds: a) do not use DataContext and create your own Model property instead or b) write your own SetDataContext method invoking an event and pray that all other devs in your team will use it instead of the DataContext setter.

Leave a Reply

Categories

Archive