DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Trending

  • After 9 Years, Microsoft Fulfills This Windows Feature Request
  • How to Convert XLS to XLSX in Java
  • Data Quality: A Novel Perspective for 2025
  • Navigating and Modernizing Legacy Codebases: A Developer's Guide to AI-Assisted Code Understanding

Why Should I Write Getters and Setters?

If most getters and setters are just indirect ways of field access, why not make the fields public and call it a day? The answer lies in future possibilities of the former.

By 
Shamik Mitra user avatar
Shamik Mitra
·
Apr. 20, 17 · Opinion
Likes (55)
Comment
Save
Tweet
Share
118.1K Views

Join the DZone community and get the full member experience.

Join For Free

When I started my career in Java, I was confused about getters and setters. One question always comes to mind: Why should I write getters/setters? It looked like some kind of weird syntax to me.

I learned that through the public access modifier, one field of a class is accessible to any packages, and with getters/setters, I am actually doing the same thing — making the field private while the getter/setter method is public, so it can be accessed by any packages.

So, what is the difference between the following two expressions?

public String name = "Shamik";

// caller:
String name = X.name;   //(X is a object instance);
X.name = "Shamik Mitra";
private String name = "Shamik";

public String getName() {
    return name;
}

public void setName(String name) {
    this.name = name;
}

// caller:
String name = X.getname();
X.setName("Shamik Mitra");


Slowly, I realized why we use getters/setters and why they are important. In this article, I share that realization.

Realization

The main difference between making a field public vs. exposing it through getters/setters is holding control over the property. If you make a field public, it means you provide direct access to the caller. Then, the caller can do anything with your field, either knowingly or unknowingly. For example, one can set a field to a null value, and if you use that field in another method, it may blow up that method with a null pointer exception.

But, if you provide a getter/setter, you provide them indirect access while taking full control. The only way to set a value is through setter, and you get a value through a getter, so now you have exactly one entry and one exit point for your field, as getter/setters are methods, which allows blocks of code, so you can do validation checks on them! The object takes the decision whether you should set the caller value or not. The same applies to a getter method — you can take the decision to return the actual reference or clone it and return the same to the caller.

So, getters/setters work as a fuse or circuit breaker — where the electric current has to be passed through the fuse. If anything goes wrong, the fuse is detached from the main circuit, so the circuit is safe. The concept is the same here. If anything goes wrong, the setter will not pass the value to a class member field.

After reading the explanation, I know still you have one question:

I understand, but generally, we do not write anything in getters/setters. We just return and set the field, which is same as exposing a field as public. So why are you saying all of this?

To answer this question, I say by writing getters/setters, we create a provision to add any validation method in the future, currently, there is no validation, but if anything goes wrong in the future we just add validation logic in the setter.

But still, it opens a debate with those who claim to be big followers of YAGNI (You Ain't Gonna Need It). They can say that when there are no such validation constraints for a field, why bother writing a getter/setter? I can simply expose it as public.

As per my understanding, The crux of YAGNI is to avoid making your code unnecessarily complex. It's like when someone tries to think big and makes their code base so generic that it welcomes any changes. But most of the changes he/she thinks of will never come.

Conclusion

Getters/setters do not make your code complex and welcome future validations. So please, go for it.

Published at DZone with permission of Shamik Mitra, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!