Why use setters/getters instead of public/private in Java

Motivation

I was reading Hatena's anonymous diary somehow the other day, and the question was written there, "Why use setter/getter instead of controlling access to internal member variables in Java public/private?" There was. I also used to write getters/setters (or use lombok) habitually, but that's why I didn't control access to member variables with public/private, and made member variables uniformly private variables. I wondered if the method was to access from getter/setter. I felt that C # and PHP do not write getters/setters as exactly as Java.

I checked it on stackoverflow

When I searched, this page (stackoverflow) was hit. The reasons for using getters/setters on this page were listed below.

  1. Encapsulation of access (get/set) processing to member variables. It can handle cases where you want to do something other than get/set when you get/set a member variable, and you can hide that process from the side that uses this class.
  2. Since the internal member variables that access through getter/setter can be hidden from the side that uses this class, it becomes possible to actually return the member variable named △△ with the name get〇〇, 3 Changes such as. Can also be made.
  3. You can change the member variables accessed through getters/setters (later) without changing the code that uses this class.
  4. Clarification of memory management and lifetime management (especially the memory discard part) of the member variables.
  5. Breakpoints can be set for the process of accessing internal member variables at runtime, so it is easier to debug the process of accessing member variables if there is a getter/setter.
  6. When calling a process such as Mocking or Serialization that assumes the existence of getter/setter in a member variable from an external library, it is convenient to use getter/setter obediently.
  7. When creating a child class that inherits the class in which the getter/setter for the member variable is defined, the access process for the member variable (getter/setter function) can be changed on the child class side.
  8. You can say getters/setters instead of passing values ​​from that class in a lambda expression.
  9. You can have different access levels between getters/setters. For example, getters are public but only setters are protected.
  10. You will be able to Lazy load and Copy on write properties.

There were also the following answers. Two weeks after the implementation (two months or two years later), I finished the implementation with public member variables, but after that, in fact, it is not enough to just set the value to the member variable, more than that when setting the value Suppose it turns out that you need to do that. If you want to implement that change, and the member variable is already referenced by 238 outer classes, you're at a loss (how to fix it).

For C # and PHP

Since C # has an automatic property initialization function, it seems that you can exchange via getter/setter without writing getter/setter in the class.

It seems that PHP can also create getter/setter functions automatically depending on the IDE, but from the viewpoint of performance, it seems that naive setter/getter should be avoided ([stackoverflow](stackoverflow). However, this was written at the time of php5, and php7 and php8 that came out after that should have significantly improved performance compared to those days, so I thought that it would be better to use setter/getter now. It was.

Even in stackoverflow, the following cases were mentioned as reasons why setter/getter should be used in PHP. You can add validation processing (even later) by defining a setter.

class Foo {
   public $bar; //I'm expecting it to be an integer type
}
$foo = new Foo;
$foo->bar = "string"; //Since it is dynamically typed, it can also be a string type.

Is setter/getter an anti-pattern?

Some have argued that (naive getters/setters) are not desirable from a readability standpoint. It seems good to avoid the situation where getter/setter functions overflow by using lombok. Some people have argued that getters/setters are anti-patterns in pure OOP. I haven't read it properly (!!), but I think I'm not saying that I should use public member variables instead, but that I should define an OOP-like function instead of using an object as a data structure in the first place. ..

Conclusion

I'm glad that it was an opportunity to look back on the meaning of what I usually do.

Recommended Posts

Why use setters/getters instead of public/private in Java
[Java] Why use StringUtils.isEmpty () instead of String.isEmpty ()
[Java] use Optional instead of if (hoge! = null) {...}
[Java] Use of final in local variable declaration
Use OpenCV in Java
Use PreparedStatement in Java
Browse class objects in Kotlin (instead of Java class name.class)
Use Redis Stream in Java
Implementation of tri-tree in Java
Use enum instead of int constant
Let's use Twilio in Java! (Introduction)
[Java] Do not use "+" in append!
Use composite keys in Java Map.
List of members added in Java 9
How to use classes in Java?
List of types added in Java 9
Implementation of like function in Java
Do you use Stream in Java?
[Java8] Proper use of Comparable and Comparator in terms of employee sorting
[Java] I participated in ABC-188 of Atcorder.
Implementation of DBlayer in Java (RDB, MySQL)
Get the result of POST in Java
Multilingual Locale in Java How to use Locale
Use OpenCV_Contrib (ArUco) in Java! (Part 2-Programming)
Use static initialization block to initialize List / Set of static fields in Java
[Java] Use cryptography in the standard library
Use "Rhino" which runs JavaScript in Java
Item 37: Use EnumMap instead of ordinal indexing
What wasn't fair use in the diversion of Java APIs on Android
[Java] [Maven3] Summary of how to use Maven3
The story of writing Java in Emacs
Role of JSP in Web application [Java]
Discrimination of Enums in Java 7 and above
The story of low-level string comparison in Java
[Java] Handling of JavaBeans in the method chain
The story of making ordinary Othello in Java
Use OpenCV_Contrib (ArUco) in Java! (Part 1-Build) (OpenCV-3.4.4)
The story of learning Java in the first programming
Measure the size of a folder in Java
Feel the passage of time even in Java
A quick review of Java learned in class
How to use JQuery in js.erb of Rails6
[JAVA] [Spring] [MyBatis] Use IN () with SQL Builder
Import files of the same hierarchy in Java
Partization in Java
Changes in Java 11
Rock-paper-scissors in Java
[Java] Use Collectors.collectingAndThen
Pi in Java
[Java] Overview of Java
FizzBuzz in Java
Summary of how to use the proxy set in IE when connecting with Java
Get the URL of the HTTP redirect destination in Java
[Java] How to use compareTo method of Date class
Omission of curly braces in if statement (Java silver)
Use of Japanese fonts and external characters in JasperReport
A quick review of Java learned in class part4
Java extracts text content of SmartArt shapes in PowerPoint
Use Java lambda expressions outside of the Stream API
[Java] Get the file in the jar regardless of the environment
Tips for making good use of Canvas in Xcode