开发者

Classes Using their Own Getters/Setters

Let's say I have the following class:

class MyClass
{
    private:

    int Data;

    public:

    MyClass(int Init)
    {
        Data = Init;
    }

    int GetData() const
    {
        return Data;
    }
};

Now, let's say I want to add a method that checks if Data is equal to zero. There are two ways to accomplish t开发者_运维问答his:

bool DataIsZero() const
{
    return Data == 0;
}

Or:

bool DataIsZero() const
{
    return GetData() == 0;
}

Which is considered better practice? I can see how just using the variable itself might improve readability, but using the getter might make the code easier to maintain.


I don't really like getters/setters for reasons that I won't go into here. They're covered in other questions. However, since you've asked about them, my answer will assume that I use getters/setters; it will not visit all the possible alternatives.

I'd use the getter, for the maintenance reasons to which you allude. Indeed, the abstraction is half the purpose of having the getter in the first place (along with the slightly tighter access control).

If using the variable is more legible than using the getter, then your getter function name is poor and should be reconsidered.

As an aside, it's best to initialise members, not assign them in your constructor body after the fact. In fact, you have to do that with constants, so you might as well start now and remain consistent:

class MyClass
{
private:
    int Data;

public:

    MyClass(int Init) : Data(Init) {}

    int GetData() const {
        return Data;
    }
};

See how the constructor has changed.


You should use the getter, because if your class moves to a more complex logic in the getter, then you will be insulated from the change. However, if your class provides a public getter, I'd question the logic of creating this method.


It depends.

The former is sufficient for simple classes.

The latter hides the implementation and can support polymorphism, if the method is virtual.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜