Pitfall - Ignoring method visibility

suggest change

Even experienced Java developers tend to think that Java has only three protection modifiers. The language actually has four! The package private (a.k.a. default) level of visibility is often forgotten.

You should pay attention to what methods you make public. The public methods in an application are the application’s visible API. This should be as small and compact as possible, especially if you are writing a reusable library (see also the SOLID principle). It is important to similarly consider the visibility of all methods, and to only use protected or package private access where appropriate.

When you declare methods that should be private as public, you expose the internal implementation details of the class.

A corollary to this is that you only unit test the public methods of your class - in fact you can only test public methods. It is bad practice to increase the visibility of private methods just to be able to run unit tests against those methods. Testing public methods that call the methods with more restrictive visibility should be sufficient to test an entire API. You should never expand your API with more public methods only to allow unit testing.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Common Pitfalls:
* Pitfall - Ignoring method visibility

Table Of Contents
8 Arrays
10 Maps
11 Strings
25 JAXB
29 Enums
32 Audio
41 Scanner
63 Logging
75 Lists
78 Sets
89 JAX-WS
93 Common Pitfalls
96 XJC
98 Process
106 Modules
114 Applets
122 JNDI
139 JavaBean
141 Literals
144 Packages
150 JMX
153 JShell
159 Sockets
167 Enum Map
175 Hashtable
177 SortedMap