rentzsch.com: tales from the red shed

Advice: Default to Protected

Java
Bill Bumgarner points out David Jeske and Brandon Long's "Python Coding Standards".

I don't currently code in Python, but this reminded me of something I run into regularly in Java:

While this is worded badly, it's trying to say that most instance variables should be private and all private variables should start with an underscore. (i.e. when in doubt make it private)

My rule, for Java, is that no instance variable should be made private unless you have a protected or public getter/setter wrappers for that ivar. Since many ivars don't deserve such a wrapper, I make them protected. Why?

  • So future subclasses can read/write them. I've run into too many cases dealing with binary-only Java frameworks where the class could have been cleanly extended to meet an unforeseen goal if only its authors didn't fall into the private-by-default trap.
  • If you can't subclass, you can fall back on reflection. Due to Java's lack of a language-level Factory pattern, quite often you can't control the class of an object being created. That means, unless the framework's author specifically added Factory support, you can't override which class is used to create an object. That, in turn, means you can't specify your important custom subclass be used instead of the original.

    However, Java's reflection allows you to access an object's protected ivars so long as you're within the same package. Thus, if your back is to the wall (search for "evil"), you can read/write the ivar even if it lacks a getter/setter. This can be a lifesaver.

Friday, March 14, 2003
12:00 AM