Concept
How can getters and setters validate values and support immutable objects?
ComputerScienceOne / Accessor & Mutator Methods
"One advantage to using getters and setters (as opposed to naively making everything public) is that you can have greater control over the values that your variables can take. For example, we may want to do some data validation by rejecting null values or invalid values. For example:\n\n1 public void setFirstName(String firstName) {\n\n2 if(firstName == null) {\n\n3 throw new IllegalArgumentException(\"names cannot be null\");\n\n4 } else {\n\n5 this.firstName = firstName;\n\n6 }\n\n7 }\n\n8\n\n9 public void setGpa(double gpa) {\n\n10 if(gpa < 0.0 || gpa > 4.0) {\n\n11 throw new IllegalArgumentException(\"GPAs must be in [0, 4.0]\");\n\n12 } else {\n\n13 this.gpa = gpa;\n\n14 }\n\n15 }\n\nControlling access of member variables through getters and setters is good encapsulation. Doing so makes your code more predictable and more testable. Making your member variables public means that any piece of code can change their values. There is no way to do validation or prevent bad values. In fact, it is good practice to not even have setter methods. If the value of member variables cannot be changed, it makes the object immutable. We’ve seen this before with the built-in wrapper classes (Integer, String, etc.). Immutability is a nice property because it makes instances of the class thread-safe. That is, we can use instances of"
Related Ideas
- How can getters and setters validate values before changing private variables?ComputerScienceOne · Accessor & Mutator Methods
- Why are getters, setters, and immutable member variables useful?ComputerScienceOne · Constructors
- How do accessor and mutator methods provide access to private member variables?ComputerScienceOne · Accessor & Mutator Methods
- How should a class manage owned collections and avoid shallow copies?ComputerScienceOne · Composition
- How can adding an addCourse method make a Student object more flexible?ComputerScienceOne · Example
- How does a constructor initialize a PHP object?ComputerScienceOne · Constructors
- What is a constructor and how is it written?ComputerScienceOne · Constructors
- What are the visibility levels used to protect Java data?ComputerScienceOne · Data Visibility