Thursday, January 13, 2011

Stardate 2011.13.1: Interfeces - Property-only Interfaces

When it comes to abstraction, I always try to be very careful. The abstraction should not dictate the types that the implementing classes should contain. This is very dangerous, and is one of the reasons that inheritance can be very dangerous. Even having a base class for a piece of data that is common to all derivatives of the base is not that wise in most instances - it is more likely that the derivative is going to either need to manage that piece of data in some way, and if it doesn't, then why have it in the base class and not in its own class that isn't in the inheritance hierarchy?

Sometimes, properties on the interfaces are somewhat useful. For instance, Ayende once mentioned to me that something like SupportsRollbacks, a boolean, is perfectly valid on an interface defining an object that can have data rolled back. However, having property-only interfaces should be a design stench in any system. I have found two ways to this same conclusion, so I think it's justified.

The first path is that, if you have an interface that is only properties, then it doesn't really manage its own data: Some other class must obviously be managing the changing of the values and so forth. When looked at this way, it's obvious that encapsulation is pantsed.

The second way is much more general in that interfaces are intended to represent some functional unit, or some specific responsibility in terms of functions. While properties in .NET are technically functions in that, when you get or set them, you have a point that you can insert code, in terms of the public-facing interface, you can't tell if it's a property or just a public variable. Of course, Visual Studio allows you to know if it is or not, but I'm talking from a purely practical standpoint here. How many times did your teacher back in CS tell you not to use public variables?

Anyway, since properties give no indication as to any functionality that they actually contain, since they often represent nouns in the system and not verbs, having interfaces that are only properties is like having a base class with only public variables.

It gets worse if the properties are custom types. What if the custom type is abstract in some way? Then you're in a real pickle (especially since those abstract types are probably just pure properties!). These are all things that I've seen on projects, and it really points out just how bad this type of system is to work with, and especially to maintain.

No comments:

Post a Comment