Getters and Setters

Burdette Lamar - Oct 13 '17 - - Dev Community

Some test automation I “inherited” a while back dealt with a textbox, labelled Brick (not quite its real name), whose getter method was called GetCurrentBrick.

Take just a moment to try to guess what the corresponding setter was called.

It was called Brk.

Nice, huh? Getter/setter pair: GetCurrentBrick and Brk.

Now if there is going to be a getter/setter pair (and I'll get to that question in a moment), the two should at least have consistent naming.

A start would be GetCurrentBrick and SetCurrentBrick.

Actually, though, the page had nothing else about bricks, so it would be better to say just GetBrick and SetBrick.

But why have two methods at all? A setter should always return the previous value, in case the caller needs to restore it. Therefore it’s simple and useful to have a single method that always gets and can, optionally, set.

Thus:

  • Brick() with no value parameter is a pure getter.
  • Brick("in the Wall") is a setter that returns the previous value.

This means there’s only one method name to learn, and it’s pretty intuitive that the value-less call is a getter, while the value-bearing call is a setter.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .