Accessor Function Pardigm

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class foo
{
    int val;

public:

    int  val() const { return val; } // get val
    int& val() { return val; } // modify val
};

int main()
{
    foo f;

    foo.val() = 20; // <-- different paradigm than I'm used to
}


I've almost always done something like foo.setVal(20). Saw some code doing it the other way and I was intrigued.
What's everyone's opinion on the former paradigm?
It seems it has the intention to break the Law of Demeter.
You are too eager to give your wallet http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf
Honestly I don't like it, because it's not cautious.

People can now set val to whatever they like and you'll probably end up checking if val is valid elsewhere.

Edit: a better observation would be, what's the point in val being private?
Last edited on
As has been mentioned... returning a nonconst reference to the variable defeats the entire point of having getters/setters. At that point you might as well just make the variable public.
I was browsing an open source project and found some code bits that used that design idiom and I wasn't sure what to think of it. I originally had the same general opinion as all of you, but I needed something to back that up.

Thanks for the feedback.
Topic archived. No new replies allowed.