Getters and setters

From CSSEMediaWiki
(Difference between revisions)
Jump to: navigation, search
m
Line 6: Line 6:
 
'''Rule for good design, version 1:'''
 
'''Rule for good design, version 1:'''
 
* Whenever you declare a field, ''foo'', make it private.
 
* Whenever you declare a field, ''foo'', make it private.
* Add a public getter called ''getFoo(), or''isFoo'' for booleans.
+
* Add a public getter called ''getFoo()'', or ''isFoo'' for booleans.
 
* Make the return type of the getter the same as the field.
 
* 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.
 
* Add a public setter called ''setFoo()'' & pass a parameter of ''foo'''s type.

Revision as of 01:57, 28 July 2008

<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(), or isFoo 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?

Some gurus go further, suggesting that we should always call getters & setters, even from inside the object containing the field. The only methods allowed to touch the field directly are its getter & setter.

Rule for good design, version 3:

  • As above, but always use the getters & setters.

This idea is explained by Ken Auer 1995. But first, it helps to realise there is more than one Encapsulation boundary behind which we might hide fields.

Personal tools