Concept
How can getters and setters validate values before changing private variables?
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 function setFirstName($firstName) {\n\n2 if($firstName === null) {\n\n3 throw new Exception(\"names cannot be null\");\n\n4 } else {\n\n5 $this->firstName = $firstName;\n\n6 }\n\n7 }\n\n8\n\n9 public function setGpa($gpa) {\n\n10 if($gpa < 0.0 || $gpa > 4.0) {"
Related Ideas
- How can getters and setters validate values and support immutable objects?ComputerScienceOne · Accessor & Mutator Methods
- How do accessor and mutator methods use this to access instance variables?ComputerScienceOne · Accessor & Mutator Methods
- Why are getters, setters, and immutable member variables useful?ComputerScienceOne · Constructors
- How does PHP visibility protect class data?ComputerScienceOne · Data Visibility
- How does encapsulation group and protect related data?ComputerScienceOne · Encapsulation & Objects
- What are the visibility levels used to protect Java data?ComputerScienceOne · Data Visibility
- How can PHP values and variable states be converted and checked explicitly?ComputerScienceOne · Type Juggling
- How do you use Java instances and invoke their methods?ComputerScienceOne · Usage