the purpose of oop using classes is to encapsulate members from the outer space.
ID: 654895 • Letter: T
Question
the purpose of oop using classes is to encapsulate members from the outer space. i always read that accessing members should be done by methods. for example:
template<typename T>
class foo_1 {
T state_;
public:
// following below
};
the most common doing that by my professor was to have a get and set method.
// variant 1
T const& getState() { return state_; }
void setState(T const& v) { state_ = v; }
or like this:
// variant 2
// in my opinion it is easier to read
T const& state() { return state_; }
void state(T const& v) { state_ = v; }
assume the state_ is a variable, which is checked periodically and there is no need to ensure the value (state) is consistent. Is there any disadvantage of accessing the state by reference? for example:
// variant 3
// do it by reference
T& state() { return state_; }
or even directly, if I declare the variable as public.
template<typename T>
class foo {
public:
// variant 4
T state;
};
In variant 4 I could even ensure consistence by using c++11 atomic.
So my question is, which one should I prefer?, Is there any coding standard which would decline one of these pattern?
Explanation / Answer
Instead of chasing guidelines for implementation nuances I suggest to look for the root motivation to have the setters and getter in the first place.
Once you understand how they help, what are the cases where there is practical difference between the forms and how it manifests, you probably can answer your question for good.
And from that point see why chasing guidelines instead of just writing the particular code to a sensible form is a bad idea.
Also if you start writing actually OO code instead of the usual faked structs related to the 'anaemic model' antipattern, you will see that a setter is an extremely rare beast, and even raw getters are not so common.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.