What variables do in private is their own business

This is another post about object oriented programming.

Ok, cool, you’re one of the 3% still reading. I just wanted to do a quick post about access modifiers on objects. It applies pretty much regardless of programming language, presuming you’re working with one that supports OO and has the standard public, private and protected for access by sub-classes only.

I think, what we need here is an attitude shift away from using private variables. Often, I see code that uses private variables and I have no idea why.

What I mean by this, is that almost every time I see a private variable, what it actually should be is a protected variable. Indeed, I think the default assumption when creating a variable, should be that you define it as protected.

Lets ignore public variables for the moment. I’ve previously argued you could simply do away with them altogether (that is what getters and setters are for), but in any case, I’m not concerned with them for this post. Lets just focus on private or protected.

The traditional teaching has always been that you should define a variable as private if you don’t want it to be publicly accessible, and giving child classes access to it later on is often an afterthought.

I don’t think this should be the case.

If we’re to adopt a true OO mindset (and it’s been around for sixty years, so given it was invented before most of us were born, you would hope we would have adopted it by now), surely you would work from a perspective that your class will be extended.

Protecting variables from external bodies makes sense, hence not making them public, but to by default place restrictions on what you can do with child classes in an OO world, doesn’t make sense to me. Why have the functionality at all? Why not make everything final if you need such protection?

That isn’t to say there aren’t plenty of instances where there is a reason to do this – but these aren’t the 90% most common use cases, so I think there is a good argument for making protected the default at least.



Don't have time to check my blog? Get a weekly email with all the new posts. This is my personal blog, so obviously it is 100% spam free.


Tags: , ,

This entry was posted on Saturday, September 29th, 2012 at 11:18 am and is filed under Limited, Programming. You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.