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?
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:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With