Friday, August 13, 2021

Why getter and setter are better than public fields in Java? Example

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 in the 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 their 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 the SDLC process, software spends more time in maintenance than development, it’s worth keeping ease of maintenance as one of the goals in development. In reality using getter and setter method in Java is one of the Java coding best practices much like using @Override annotation while the overriding method in Java.


Main problem with making field public instead of getter and setter is that it violates Encapsulation by exposing the internals of a class. Once you are exposed internals of class  you can not change internal representation or make it better until making changes in all client codes. 

Since every code change comes with risk and the cost of regression testing is high during maintenance, its not a good idea to make the 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 the getter and setter method in Java?

What is getter and setter method in Java vs public modiferFor those who are new to Java and not very familiar with Java terminology, getter and setter method means a 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 the particular field is initialized and provided to the client which makes the validation and debugging much easier. you can simply put breakpoints or print statement to see which thread are accessing and what values are going out.

On the validation front, you can easily avoid an incorrect value for a particular field, i.e. if the field is non-nullable then you can throw NullPointerException or IllegalArgumentException. with the public field, your client code will break when it starts 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 libraries and framework e.g. display tag. which uses a 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 methods and return what makes more sense in the context of sub class.

Though I agree it makes code more verbose and there are certainly cases where the use of public field make sense. As we said by making a class field public violates Encapsulation but what if the Class in question is a 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 the worst case if requirement changes come 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 the field private and final unless otherwise, you have a very good reason not to do so. making fields private and providing getter and setter are standard Java coding standards and allows your code to be compatible with other frameworks which use 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