Private vs Protected

Posted by Uncle Bob on 01/21/2007

Someone on comp.object recently asked why anyone would make a field private since privacy ruins extensibility.

I recently read an article on comp.object that asked the following question:

While I can see that the ‘private’ modifier has its uses, I’m puzzled as to why it’s advocated so much given that one of the strong points of OO is extensibility.

I responded with:

The Open-Closed Principle of OOD (See article) says that objects should be open for extension but closed for modification. In other words, you should be able to change what a module does without changing the module. Extensibility, in OO, is best achieved when you keep the code you are extending safe from modification.

How do you protect a module from the forces that would try to modify it? One technique is to keep the variables that module depends upon private. If a variable is not private, then it is open to be used in a way that the module that owns that variable does not intend. Indeed, using a variable in an unintended way is the only reason to make the variable public or protected. But when you use a variable in an unintended way you likely force modifications into the owner. If, on the other hand, all the variables of a module are private, then no modification can be caused through unintended useage.

Privacy does not preclude extensibility. You can create public or protected accessor methods that: 1) provide extenders access to certain variables, and 2) ensure that the extenders don’t use the variable in an unintended way.

For example, given a variable v used by a module m, such that v should never be negative. If you make v public or protected someone could set it to a negative number breaking the code in m and possibly forcing mofidication to m. However, if v is private but is accessible through getV and setV methods; and if the setV method throws an exception if you pass it a negative number, then m is safe, and extenders are forced to follow the rules that m expects.

To be fair, while I am a big proponent of keeping variables private, I have also come to rely much more on my unit tests to enforce the appropriate use of variables. When the code enjoys 90+% unit test coverage those tests will uncover and prevent variable misuse. This softens the need for the compiler to enforce privacy. This is not to say that you should not make your variables private, you should. It is to say that if you use TDD, the cost/benefit ratio changes, and you may find that you can soften access to some variables.

Comments

Leave a response