Tip #4: Stop and Think before you make that Class public
By ByronNevins on Aug 09, 2011
I run into this time-wasting situation fairly frequently:
I need to change the signature of a Java class, in GlassFish, that has been declared public. Uh-oh! It's public so I can't just change it.
So -- my first step is to grep through every single java file in GlassFish. That means 7,772 files currently!
Now I have to wonder -- is the class being used from modules outside of GlassFish? Uh-oh -- now I have to run massive automated tests to make sure I don't break something.
Ultimately you can never be totally sure that public class is not being used somewhere. E.g. say the name of the class is FooGooHoo. What if there is code doing a Class.forName("Foo" + "Goo" + "Hoo") ? I'll never find it with a simple search.
This is all expected stuff with the public keyword. But what if the class is exclusively used inside of its own package? Then I just wasted a whole lot of my employer's money chasing down non-existent references.
On the other hand if the class had its visibility set to pkg-private in the first place, all I had to do was to search inside that one package for uses. Java guarantees no other package can see it. And if other code somehow subverts that policy -- tough!!
Moral of the Story:
Only mark classes and methods as public when you are absolutely positively sure that it must be public. When in doubt make it pkg-private and avoid protected too.