Showing posts with label to be served and protected. Show all posts
Showing posts with label to be served and protected. Show all posts

Wednesday, May 27, 2009

Java Methods: protected is the new private?

In code reviews (including my code), when I see a Java method marked as private, I ask if there are any unit tests for it.

Since tests are written in other files in parallel packages, the answer, of course, is no.

I've recently realized that I've obtained the following habit: my methods are either public or protected. I have no use for default or private. I don't like default because I feel compelled to write a comment saying that it is package-level access; I don't like private because of the lack of testing options.

Before you start hammering in comments, here are some thoughts:

  • This is not for a formal API to another team or other 3rd party. In that case, I would be more careful and rigid. You may argue there is no distinction, in which case: commence hammering.
  • I realize that protected is not default and that it is leaking encapsulation somewhat. I can cheerily say that I don't care. I like scanning a file and seeing either public or protected.
  • I'm not trumpeting that I write more unit-tests than others on my team. Just because a method is protected doesn't mean that I've written the tests!
What do you think? Has your style changed over the years, with respect to access modifiers on methods?