Not using get/set….

November 13th, 2005 by Hen

Just read Bob Lee’s blog entry on getters and setters.

I recently worked on a project in which I decided to re-evaluate the public get/set and private attribute rule. I’ve always found the get/set bit quite clunky, but I’m a strong believer in the need for idiomatic Java at work, so I stick with it. One place this causes problems is when the C++ using R&D department try to look at the code; the gets/sets seem to confuse them. As this project involved a lot of R&D viewing of the code, I tried the following.

Firstly I ditched having the public methods and created classes with anonymous/package scope and anonymous/package scoped variables. My code therefore gives off warning flags to all Java developers with: “measurement.timestamp = new java.util.Date()” etc. This worked pretty well, and by not allowing the classes to be seen outside of their package, I limited the amount of perl search and replace needed to handle a renaming etc.

Pretty soon though I wanted to have multiple packages and data classes that passed between the packages. So I turned to my preference, methods with the same name.

    private int age;

    public int age() { return this.age; }
    public void age(int i) { this.age = i; }

Leading to the beautiful yet equally terror-inspiring to the idiomatic programmer, measurement.timestamp(new java.util.Date()) and Date date = measurement.timestamp().

End of the day, set/get win because it’s better to be readable and lame, than succinct and confusing. Plus the R&D guys will still just complain.

3 Responses to “Not using get/set….”

  1. Chris Winters Says:

    Plus, Java people won’t like it because it’s very Perlish :-) (Class::Accessor and multiple other CPAN modules use this idiom for object property manipulation…)

  2. Tom Says:

    Just make them public fields and use Eclipse for renaming/encapsulation as needed.

    Be more careful for APIs that you want the general public to use, but for internal stuff, public fields usually work just fine. (And sometimes even for external APIs, but again, you have to be careful.)

  3. Tim O'Brien Says:

    Who are these R&D people you speak of, and why do they feel qualified to comment on the greatness that is Java?