Daily Archives: 10.11.2017

Coding

Package visibility is the best visibility in Java

I find the best visibility level in Java to be the default visibility i.e. package visibility, because it enables unit test classes to access all the methods, if the test is placed in the same package as the main class.

Also package visibility is shorter to write since you can omit the visibility declaration, so there is less boiler plate.

The second best visibility level is protected, since in some cases you can create your test classes as sub-classes of your main class. However, as stated before, package visibility works better in most cases, if you use packages properly.

Third, typically if you run Sonar and do code review and static analysis on large projects, I have found out that typically 80% of the methods are public, and 20% are private/protected. Thus, the main idea of using private or protected methods is to protect the data/properties from being accessed by bypassing the accessors. Most of the methods will be typically public anyways.

The most useless visibility level (but unfortunately commonly used) is private as it’s impossible to test (without using Reflection and modifying the visibility to something else). Also, private prohibits code re-use in subclasses, which is the main idea of using object oriented paradigm in the first place, and thus should be avoided. For the same reasons keyword final should be avoided in most cases.

Thus, I find your example to be the best practice how to define the visibility levels :). However, you are missing the package declaration and unit tests.

See https://stackoverflow.com/questions/16727414/the-use-of-visibility-modifiers-in-java/47213314#47213314

Published by: