DEV Community

Burdette Lamar
Burdette Lamar

Posted on

Getters and Setters

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.


  • 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.

Top comments (1)

kspeakman profile image
Kasey Speakman

This was (is?) a pretty common way to do things in Javascript. However, it is encoding two different behaviors in one method name. The users of this code still have to remember the two distinct usages and their different outcomes. It being behind one name (and a noun for a method) makes it less intuitive / require some investigation to make sure I'm calling it right. (Especially after I come back to it months later and forgot.) GetThing and SetThing are pretty boring, but usage is obvious. (Although I am not a fan of getters and setters in general.)

I could not agree more about the naming. And nice first post here!