Tuesday, December 4, 2012

Why getter and setter are better than public fields in Java

public modifier vs getter and setter method in Java
Providing getter and setter method for accessing any field of class in Java may look unnecessary and trivial at first place, simply because you can make field public and it’s accessible from everywhere in Java program. In fact many programmers do this in there early days but once you start thinking in terms of enterprise application or production code, you will start seeing how much trouble it can create in terms of maintenance. Since as per SDLC process, software spends more time in maintenance than development, it’s worth keeping ease of maintenance as one of goal in development. In reality using getter and setter method in Java is one of the Java coding best practice much like using @Override annotation while overriding method in Java. Main problem with making field public instead of getter and setter is that it violates Encapsulation by exposing internals of a class. Once you exposed internals of class  you can not change internal representation or make it better until making change in all client code. Since every code change comes with risk and cost of regression testing is high during maintenance, its not a good idea to make field public in Java.  In this Java tutorial we will see some more benefits getter and setter offers over public fields in Java.

What is getter and setter method in Java

What is getter and setter method in Java vs public modiferFor those who are new in Java and not very familiar with Java terminology, getter and setter method means method for accessing and modifying any property of a class in Java. For example in Counter class if we have a count variable than getCount() is getter method and setCount(int count) is a setter method in Java. Let’s see How much difference decision of making properties of class public makes over providing getter and setter method in Java.

1) getter and setter method gives you centralized control on how a particular field is initialized and provided to client which makes validation and debugging much easier. you can simply put a breakpoints or print statement to see which thread are accessing and what values are going out.

On validation front, you can easily avoid an incorrect value for a particular field, i.e. if field is non nullable than you can throw NullPointerException or IllegalArgumentException. with public field your client code will break when it start using that field without knowing which part of your code is setting incorrect or null value.

2) By making fields private and providing getter and setter and following java bean naming convention you make your class usable with many open source library and framework e.g. display tag. which uses combination of reflection and Java bean naming convention to dynamically load and access fields.

3) with getter and setter you give an opportunity to Subclass to override these method and return what makes more sense in context of sub class.

Though I agree it make code more verbose and there are certainly cases where use of public field make sense. As we said by making a class field public violates Encapsulation but what if Class in question is private nested class or package private class, In that case they are well encapsulated and giving getter and setter can be avoided if you are not doing any validation and simply setting and getting value. Even in worst case if requirement changes comes and you need to perform sophisticated validation you can do this because all client code is within your reach.

So this was one of the best coding practices to follow on Java. Always try to make field private and final unless otherwise you have very good reason of not to do so. making fields private and providing getter and setter are standard Java coding standard and allows your code to be compatible with other framework which uses reflection.

Other Java articles you may like
Java mistake to avoid – using double and float on monetary calculation

3 comments :

Ruslan said...

Indeed using getter and setter methods in Java are good Idea. You could possibly add following reason into your list in support of using getters and setters :

1) Validation : By using Setter method, you get a place to validate input or value set to the field. You can check null, empty and range of values at one place before assigning it to field or property. If you don't use setter method, than either you miss critical validations or duplicate validation logic at many places, wherever you set value of public field.

2)Encapsulation : Making a field public breaks encapsulation as you are exposing internals of your class to outside world. For example, You may have been HashMap as your cache, if you expose that detail as public field you may never be able to replace HashMap with ConcurrentHashMap or any better implementation. By using Getter and Setter method in Java, you encapsulate internal details of class.

3.By using getter method in your class, you get a chance to return copy of mutable fields to outside world e.g. Date. Had you expose Mutable fields as public API, you running risk of unintended or malicious modification of internals of class.

This is my answer to all Java developers who ask When to use getters and Setters, why getter and setter method in Java or what is the use of setter and getter methods in java.

I always use getter and setter method in my code and with Eclipse, you can generate geter and setter method in seconds.

-Ruslan

InsomaniacK said...

I believe validation should not be done in setter. That should be part of calling logic.
Moreover when using setter for arrays, we should be careful and return copy of the array

Anonymous said...

@Ruslan
The example for no.2 is not on the spot, that situation can easily be avoided if you declare the field as Map, then you can switch the implementation at your discretion.

Post a Comment