Basic Mistakes of Writing Getters/Setters in Java

Well, after reading the title, first thought which comes to mind is “Is there a guideline for Getter/Setter in java?” .

The answer is “No, there isn’t, this blog entry is my mistakes done during my last 10 years of coding (or many times people refer to it as “experience” :D)”.

So let's get started, I will not go into details of what, why, how etc of object oriented programming and where do getter/setter fit in, but if you google it out, you will find detailed explanations on these topics.

Mistake No 1: Is assigning the object reference directly into the Setter of business objects.

For example: Consider a Employee class having int[] array of employeeIds with a default setter coded for it. Assume below code is written in some method:

Hence I will always recommend to write setter like below :

Mistake No 2 : Is returning the object reference directly from the Getter for business objects.

Suppose somewhere in the business logic the code is as follows :

Hence to fix the above issue, I would recommend to write the getter as follows:

Mistake No 3. Writing Getter/Setter for mutable Java data types e.g java.util.Date. or Calendar etc.

Java has some mutable data types e.g Date, Calendar etc, if any one resets the value using a get method or using a reference method , it becomes a huge maintainability headache while debugging(searching using method references can turn out to be an ardent task).Hence I would always recommend to always write getter and setter using defensive copy i.e deep cloning.

Mistake No 4: Getter/Setter for Collection of business objects.

As mistake no 3 points out cloning for mutable data types of java this is also applicable for mutable business object or mutable collection of objects.

Lets say every employee works on multiple Project so with in each Employee object we hold a list of Project, keeping the above in mind to always return a copy we write our getter/setter as follows :

But there is a flaw which can be exposed as follows:

So to avoid the above mistake always implement clone method with deep cloning as follows :

And in Employee Class

Mistake No 5 : Getter/Setter is required for private scope, they are pretty much useless if provided for public scoped variable.

This is self explanatory, this mistake seldom happens but needs to be taken care.

What am I missing here ? Let me know in comments section and I'll add in!
What’s next? Subscribe Learn INQuiZitively to be the first to read my stories.