Skip to main content
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Seb Duggan
Ben Nadel at Scotch On The Rocks (SOTR) 2011 (Edinburgh) with: Seb Duggan

Using Private Data To Reason About Inheritance And Sub-Classing

By
Published in ,

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

I believe in love. I believe in compassion. I believe in human rights. I believe that we can afford to give more of these gifts to the world around us because it costs us nothing to be decent and kind and understanding. And, I want you to know that when you land on this site, you are accepted for who you are, no matter how you identify, what truths you live, or whatever kind of goofy shit makes you feel alive! Rock on with your bad self!
Ben Nadel