VOOZH about

URL: https://dzone.com/articles/java-encapsulation

⇱ When the Getter and Setter Became Your Enemy


Related

Java’s Encapsulation - When the Getter and Setter Became Your Enemy

We know that we should reduce the visibility of the field as much as possible, but it will be a waste if you have a data breach when we put getter and setter to all methods as public.

By Jun. 29, 22 · Presentation
Likes
Comment
Save
8.5K Views

Join the DZone community and get the full member experience.

Join For Free

Encapsulation is the key to a good code design, but how to archive it? Java developers automatically think about putting getter and setter in a private attribute. 

The encapsulation is a wrapping up of data under a single unit. It is the way to protect the data with OOP and avoid any security issues. The main idea around encapsulation is the data's guardian or a shield from being accessed by the code outside this shield when it makes sense. 

In the clean code, we have Uncle bob when he talks about the significant difference between structure code from OOP is the OOP you hide the data to expose the behavior.

Using a good encapsulation, we have several advantages: 

  • Data Hiding
  • Increased Flexibility
  • Reusability
  • Testing code is easy

We know encapsulation is essential from those points and many more aspects we did not put in this article. The challenge of this topic is how to apply it. 

We usually think about getter and setter as the primary way to archive it; however, sometimes, those methods affect the model, doing the same result as a public field, so de-encapsulation the entity.

Nevertheless, it is the same path to either POJO or the anemic model, making us go away from good code. 

We know that we should reduce the visibility of the field as much as possible where the higher priority is the private, but it will be a waste if you have a data breach when we put getter and setter to all methods as public.

Join us today and understand why blindly applying getter and setter are the worst solutions to encapsulation and what you should use instead. 

Encapsulation (networking)

Opinions expressed by DZone contributors are their own.

Related

  • Best Ways to Write Clean and Quality Python Code
  • Unraveling Lombok's Code Design Pitfalls: Exploring Encapsulation Issues

Partner Resources

×

Comments

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

Let's be friends: