Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is more appropriate: getters and setters or functions?

Is it ever appropriate to abandon the "getMyValue()" and "setMyValue()" pattern of getters and setters if alternative function names make the API more obvious?

For example, imagine I have this class in C++:


public class SomeClass {
private:
    bool mIsVisible;

public:
    void draw();
    void erase();
}

I could add functions to get/set "mIsVisible" like this:


bool getVisible() { return mIsVisible; };

void setVisible(bool visible) { if (!mIsVisible && visible) { draw(); } else if (mIsVisible && !visible) { erase(); }

mIsVisible = visible;

}

However, it would be equally possible to use the following methods instead:


bool isVisible() { return mIsVisible; };

void show() { 
    if (!mIsVisible) {
        mIsVisible = true;
        draw();
    }
}

void hide() {
    if (mIsVisible) {
        mIsVisible = false;
        erase();
    }
}

In brief, is it better to have a single "setVisible(bool)" method, or a pair of "show()" and "hide()" methods? Is there a convention, or is it purely a subjective thing?

like image 713
Ant Avatar asked Oct 06 '08 17:10

Ant


1 Answers

Have a read of the article "Tell, Don't Ask" over at the Pragmatic Programmers web site and I think you'll see that the second example is the way to go.

Basically, you shouldn't be spreading the logic out through your code which is implied with your first example, namely:

  1. get current visibility value,
  2. make decision based on value,
  3. update object.
like image 163
Rob Wells Avatar answered Sep 23 '22 07:09

Rob Wells