Archive for August 26th, 2006

In Defense of Protected Variables

Saturday, August 26th, 2006

Yakov Fain argues at JavaLobby that there’s no good use for protected variables, even going so far as to ask in a comment response

If someone decides to create a brand new object-orient programming language, should s/he even include the keyword protected there?

This seems surprisingly naive from someone with Yakov’s experience. We need more access levels in Java, not fewer. It’s a huge pain that protected variables are also package-default, and there’s no friend concept like in C++. But that’s a rant for another day.

I often put a line like this in an abstract base class:

protected transient final Logger _log = Logger.getLogger(getClass());

Then all subclasses get logging for free – no need to build up a logger instance because it’s already done for you. I could have made the field private and created a protected accessor – getLogger() – but why bother?

It’s not static, so I can use the runtime class (getClass()) instead of hard-coding the base class, e.g.

protected transient static final Logger LOG = Logger.getLog(BaseClass.class);

This would be very bad – all subclasses would log as “BaseClass” and reading log files I wouldn’t know what subclass was actually sending the message.

Protected fields are great for constructor parameters that are used by the class and subclasses but aren’t part of its public API, e.g.

protected final Parser _parser;
protected final Helper _helper;
protected BaseThing(Helper helper, Parser parser) {
  _parser = parser;
  _helper = helper;

In this case I could make the fields private with protected accessors, but again, why bother? And I certainly wouldn’t automatically make a public accessor for them, unless the design requires it. If I only need these objects for internal use, why publish them? If they’re not immutable, then I’d need to make defensive copies even though they’re final. All huge overkill for class/subclass-internal fields.

To address the specific concern of Yakov’s original post, it looks like there’s a disconnect between what the framework developers and Yakov consider public data. Either they were overzealous in hiding access, or Yakov is misusing the API in ways not intended by the original design. It’s impossible to know because he didn’t cite the actual code or even the framework that he’s talking about. So this is more of a generic defense for protected methods and variables. They’re very useful in some cases, and not applicable in others. So if you don’t understand this or have no use for them, don’t use them.

Creative Commons License
This work is licensed under a Creative Commons Attribution 3.0 License.