Sunday, November 22, 2009

Better Alternative for Getter/Setters?





Recently lombok project has created
quite a buzz. It is a very nice project which lets one put short and concise annotations in place of getter setters. There are other projects also which takes this approach which has similar annotations in place. With the annotations no explicit getter setters are not necessary and still other classes can call the getter setters as if they are there. The lombok project also fits into eclipse ide which makes the getter setters appear as code completion even though they are not there.

Could there be a better alternative? How about having annotation similar to lombok project and let's say they called @Getter & @Setter which will create the getter and setter implicitly so other classes can call the methods and not get compilation error. What if @Getter annotation makes the field public for reading purpose and @Setter annotation makes it public for writing purpose. So if a field is annotated with @Getter then one should able to do
  • something = instance.field,
where instance is the instance of the class and field is a private field in the class. And if it is annotated with @Setter, one should be able to do
  • instance.field= something.
With both @Getter & @Setter annotations, one will be able to use them essentially as public fields. Java IDEs will have to change to make this work. In particular, refactoring will probably be difficult, but it will be well worth the effort for the simplicity it brings.

In addition to not having the getter/setters, this will also make it apparent which fields are really private and which are modifiable and accessible. One does not need to scroll down hundred lines to see if there are getters setters for it. An optional body could be supplied to the annotations as well. But in most cases, simple return field (for getters) and this.field = field(for setters) will do.

The two
annotations can be combined to one annotation called @GetterSetter. A @Data annotation can be created as well just like lombok project does which will make all private fields having @GetterSetter annotation. To be complete, a negative annotation @NotGetter @NotSetter can be applied to few fields which are not supposed to be accessible and modifiable.

Another
useful annotation to cut code clutter can be to introduce @Constructor annotation which can be attached to a class. This can take optional parameters @Constructor(field1, field2, field3,..). There can be multiple Constructos with varying numbers of fields. This could be extended to equals, hashCode, and toString methods as well. For these methods, a template could be defined which will present in the classpath. I am not providing further details for simplicity.