Sunday, March 2, 2014

The Orthodox: Java getter and setter

Let me start by saying, 'I hate it'. I always wrote it for the sake of writing it. Before making any decision I would like to bounce it with the community.

In the recent years most of us write Java classes that fall into one of these categories.

1. The so called POJO - Only attributes with getters and setters. Mostly used for serialization/de-serialization (to DB row, to JSON, to XML or any thing). - The carriers

2. The business processing classes where we tend not to have any instance variables. These are like the singleton instances doing the processing accepting/returning some POJO. - The performers


class Customer {

public Integer addCustomer(MyCustomerBean bean) {

public MyCustomerBean get(Integer custid) {

So there is no instance variable dependency between two methods.

Further we get details from multiple such POJOs (e.g. MyAccountBean, MyCustomerBean) and put it into another POJO that is response to a service or UI call. These days annotation based mappers are quite famous, which would give you ResponseVO from  MyCustomerBean and MyAccountBean with a single line of code. I do remember how much tough life was without them (e.g. Castor for XML)

In none of these classes, ResponseVO, MyCustomerBean or MyAccountBean, the getters and setters do anything other than getting the variable and setting the variable. Is there any reason for which we keep doing it and blame it on to encapsulation??

Give me any good reason they are required for and yet they occupy 30-40% of your code! Thanks to eclipse to provide us with getters and setters generators. Just to add to the misery we add javadocs to such code ( again thanks to the auto javadoc generators).

Let's think whether they are required for our POJOs' or not? Can we have our POJO attributes public and lessen the pain.

Do I suggest having the Customer class with all the attributes and associated methods? Probably not. Today MyCustomerBean might a hibernate dependent bean and tomorrow it may be Toplink based. Let's give getters and setters a peaceful send off.

It may sound touche but YAGNI principle is really important to follow when the life of a code is too small to think about improvements, mostly it is re-writes.

What if I need to add a logic in my getters and setters won't help! :)

Code less that makes sense!
Happy Coding!

No comments: