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.