Trying to reduce Java getter/setter boilerplate code

By Steve Claridge on 2014-08-26.

A common complaint with Java is the amount of boilerplate code that has to be written to encapsulate class fields with getter and setter methods. Most people will write a getName() and setName() function for each of a class's fields that they want exposed, which results in a lot of code. A question for you: how many times have you actually put any meaningful code into a getter or a setter? If you are anything like me then the answer is almost never .

Whilst it makes sense to encapsulate internal state by making a class's fields private and using a getter and setter, it does not make sense to write have to write this every time:

class Oldstuff
{
  private String filename;   public String getFilename()
  {
    return filename;
  }   public void setFilename( String n )
  {
    filename = n;
  }
}

So I've started writing my classes a little differently so that I can reduce the amount of pointless boilerplate code:

Class Newstuff
{
  private String filename;   public String filename( String... f )
  {
    return f.length > 0 ? filename = f[0] : filename;
  }
}

And here's the difference in calling these two, the second is a little cleaner in my opinion:

Oldstuff o = new Oldstuff();
o.setFilename( "/tmp/hello.txt" );
System.out.println( o.getFilename() ); Newstuff n = new Newstuff();
n.filename( "/tmp/hello.txt" );
System.out.println( n.filename() );

The second way has a variable argument, if you specify a value then the function behaves as a setter, if not then it behaves as a getter. This way of doing things is not perfect, you can't specify your setters as chainable methods and the if.length > 0 check on the variable argument looks a little messy at first glance but doing it this way does cut down on class size significantly.