Bifalgorithm post · Computer science one · Accessor & Mutator Methods

How can getters and setters validate values before changing private variables?

How can getters and setters validate values before changing private variables? (Computer science one · Accessor & Mutator Methods) — "One advantage to using ge…

Ideas in this flowchart

  • Getters and setters provide greater control over variable values than making everything public.
  • Making everything public exposes variables without the same level of control.
  • Setter methods can control which values are accepted.
  • Data validation can reject unacceptable values.
  • Null values may be rejected.
  • Invalid values may be rejected.
  • The setFirstName method validates the first-name value.
  • A null first name causes an exception stating that names cannot be null.
  • A non-null first name is assigned to the firstName variable.
  • The setGpa method treats values below 0.0 or above 4.0 as invalid.
Feed/

How can getters and setters validate values before changing private variables?

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

Flowchart preview
👍
0
0 comments0 shares

Sign in to view and post comments.