Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The idea behind using getters and setters is to be able to perform other behavior than <em>just</em> setting a value. This practice is recommended because there are a multitude of things you might want to retrofit into your class.</p> <p>Common reasons to use a setter (there are probably more):</p> <ul> <li><strong>Validation</strong>: not all values allowed by the type of the variable are valid for the member: validation is required before assignment.</li> <li><strong>Invariants</strong>: dependent fields might need to be adjusted (e.g. re-sizing an array might require re-allocation, not just storing the new size).</li> <li><strong>Hooks</strong>: there is extra work to perform before/after assignment, such as triggering notifications (e.g. observers/listeners are registered on the value).</li> <li><strong>Representation</strong>: the field is not stored in the format "published" as getters and setters. The field might not even stored in the object itself; the value might be forwarded to some other internal member or stored in separate components.</li> </ul> <p>If you think your code will never, <em>ever</em> use or require any of the above, then writing getters and setters by principle is definitely <em>not</em> good practice. It just results in code bloat.</p> <p><strong>Edit</strong>: contrarily to popular belief, using getters and setters is unlikely to help you in changing the internal representation of the class unless these changes are minor. The presence of setters for individual members, in particular, makes this change very difficult.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload