Do you use default visibility (package) in Java?

The default visibility in java means that only other classes in the same java package can access it. Of course, I see its use and have used it several times.

On the other hand, 90% of the default visibility that I come across is just a developer who forgot to add any visibility keyword.

So, on the one hand, this is legal use, on the other hand, it often disguises bad code. What do you do in your development teams?

+4
source share
3 answers

Usually I try to get everyone to start with the most limited amount and only begin to expand outward if we see that it is necessary in the design. Sometimes the decision to switch from private to package-private also due to our need to write tests without having to go the way of using a mocking structure (see Powermock ).

To add to this, we follow the same mentality regarding variability. It all starts with final , and only when we see the need for a state change, will we delete it.

+10
source

If I specifically want to access the package, I put / * package * / before defining a method / variable, etc., so that people know that I actually meant it, and not be lazy. I rarely use it, though.

+5
source

I encourage people to use private , which I would rather be the default.

From time to time, I run code analysis that reduces access modifiers only to what is needed.

+4
source

All Articles