Getters and setters

From CSSEMediaWiki
Revision as of 04:54, 25 July 2008 by Warwick Irwin (Talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

<Long tedious background explanation of getters & setters goes here>

Getters are also known as accessors. Setters are also known as mutators.

Rule for good design, version 1:

  • Whenever you declare a field, foo, make it private.
  • Add a public getter called getFoo(), orisFoo for booleans.
  • Make the return type of the getter the same as the field.
  • Add a public setter called setFoo() & pass a parameter of foo's type.
  • Inside the object, access the field directly.
  • Elsewhere, use the getters & setters.

Simple.

Except we just killed Encapsulation.

Rule for good design, version 2:

  • As above, but only add the getters &/or setters as necessary.

If the type or name of foo changes, should we change the methods too?

If we do, are we Information hiding?

Personal tools