Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessors in java [duplicate]

Tags:

java

I'm wondering about why to use getter and setter methods in java. If you can read or modify values of private fields via getters and setters, why not just changing them directly to public? I know that getters and setters have to be reasonable, but what would be the straight answer that it's not possible to give up on them?

like image 700
user2095107 Avatar asked Dec 21 '22 09:12

user2095107


2 Answers

Some reasons are:

  • You can add additional constraints and checks. For instance, if a particular integer attribute must be in the range [10..20], you can easily add a check to the setter to ensure that no other values are set on the attribute.
  • You can make them "read-only" by providing a getter only.
  • You can easily set a source breakpoint on the setter to see when and from where the value is modified.
  • You can easily add logging to trace which values are ever set.

See the answers in the link provided by @Aditi for additional reasons: Why use getters and setters?

like image 99
Andreas Fester Avatar answered Jan 08 '23 05:01

Andreas Fester


One of the hardest forms of bug to track down is an unexpected, inappropriate change in the value of a data item.

If the data is public, the code that makes the change could be anywhere in the program.

If it is private, the code that makes the change must be in the same source file, typically the same class. It is easy to find and instrument all code that could possibly change it, including its setter.

like image 36
Patricia Shanahan Avatar answered Jan 08 '23 05:01

Patricia Shanahan