Private considered harmful

Comment

Coding

Time after time I explain to the other coders that private visibility is harmful, 95% of coders tend to try rock hard claim otherwise. Unfortunately private is a harmful visibility level to use.

Personally I haven’t yet found any legitimate use case for private -visibility, but the opposite. Quote from the documentation of a unit testing framework:

Limitation: final, private, and static methods
Please note that final, private and static methods cannot be stubbed or mocked.

Using protected visibility instead of private by default has the advantage of leaving the opportunity for the future developers open to reuse and extend your code. Using private denies this opportunity and forces rewrite of your code. For test classes using protected is however clumsy, since you need to create a subclass to be able to mock or stub the methods or properties you want. Using dependency injection would be a better idea.

PHZ.fi has been conducting a range of code reviews for half a dozen large softwares with 150-600k lines of code. My surprising observation has been that in all the cases the code has been consisting 80% of public methods. The real life outcome thus seems to be that coders don’t really use encapsulation so often and limiting the visibility on class level is less common than using hidden interfaces (e.g. private). Of course a function is also an interface for encapsulation, and thus the one can also deduct that the coders are mostly hiding the implementation details inside one or only a few public methods rather than using large number of private methods.

In Java my best practice is to define all non-public properties and methods on package -visibility, meaning that there is no public, protected or private. If you place your test class in the same package, you can easily access also the non-public the methods or properties and for most of the time you don’t even need DI configurations.

Leave a Reply