Bifalgorithm post · Computer science one · Accessor & Mutator Methods

How can getters and setters validate values and support immutable objects?

How can getters and setters validate values and support immutable objects? (Computer science one · Accessor & Mutator Methods) — "One advantage to using getter…

Ideas in this flowchart

  • Getters and setters provide controlled access to member variables.
  • They provide greater control over the values that variables can take than public variables do.
  • Data validation can reject null or invalid values.
  • The first-name setter rejects a null first name.
  • A null first name causes an IllegalArgumentException.
  • The GPA setter accepts only values from 0.0 through 4.0.
  • A GPA outside the range [0, 4.0] causes an IllegalArgumentException.
  • Controlling member-variable access through getters and setters is good encapsulation.
  • Encapsulation makes code more predictable and more testable.
  • Public member variables can be changed by any piece of code.
  • Public member variables provide no way to validate or prevent bad values.
  • It can be good practice not to provide setter methods.
  • If member-variable values cannot be changed, the object is immutable.
  • Immutability makes class instances thread-safe.
  • Built-in wrapper classes such as Integer and String are examples of immutable classes.
Feed/

How can getters and setters validate values and support immutable objects?

No cover

Channel

Computer science one

1 page

"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"

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.