Ben Nadel
On User Experience (UX) Design, JavaScript, ColdFusion, Node.js, Life, and Love.
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with: Gabriel De La O
Ben Nadel at CFUNITED 2010 (Landsdown, VA) with: Gabriel De La O

Using Private Data To Reason About Inheritance And Sub-Classing

By Ben Nadel on

Over the years, I've definitely learned to favor composition over inheritance. But, sometimes, I really feel like components should be sub-classed. Of course, that doesn't mean that my feelings are right. What I'd love is some sort of constraint that makes it easier to reason about sub-classing. And, this got me thinking about private data access.

Last year, when I was re-reading the Fundamentals of Object-Oriented Design In UML by Meilir Page-Jones, I came across the constraint that a sub-class should not access the private data in its super-class. This makes it easier to reason about access; but, coming at it from the other direction, I think this constraint may also make it easier to reason about sub-classing in general.

If a sub-class cannot access the private data of its super-class, then I think it stands to reason that if a sub-class cannot implement a feature without accessing the private data in its super-class, the sub-class probably shouldn't be a sub-class in the first place.

Of course, you can always rework a super-class to expose more data in order to make it more conducive to sub-classing; but, if you start to break encapsulation just for the sake of sub-classing, that's probably not such a great idea either. You have to make sure that exposing data doesn't allow the state of the super-class to be compromised.

Now, I know that computer science is more of an art than a science; but, like a child, I enjoy constraints. They make me feel safe. And this constraint makes me feel safe when it comes to thinking about sub-classing components.

Reader Comments