class - Simple C++ getter/setters -
lately i'm writing getter , setters (note: real classes more things in getter/setter):
struct { const int& value() const { return value_; } // getter int& value() { return value_; } // getter/setter private: int value_; };
which allows me following:
auto = a{2}; // non-const object // create copies "default" (value returns ref!): int b = a.value(); // b = 2, copy of value :) auto c = a.value(); // c = 2, copy of value :) // create references explicitly: auto& d = a.value(); // d ref a.value_ :) decltype(a.value()) e = a.value(); // e ref a.value_ :) a.value() = 3; // sets a.value_ = 3 :) cout << b << " " << c << " " << d << " " << e << endl; // 2 2 3 3 const auto ca = a{1}; const auto& f = ca.value(); // f const ref ca.value_ :) auto& g = ca.value(); // no compiler error! :( // g = 4; // compiler error :) decltype(ca.value()) h = ca.value(); // h const ref ca.value_ :) //ca.value() = 2; // compiler error! :) cout << f << " " << g << " " << h << endl; // 1 1 1
this approach doesn't allow me to:
- validate input setter (which big but),
- return value in const member function (because want compiler catch assignment const objects:
ca.value() = 2
). update: see cluracan answer below.
however, i'm still using lot because
- most of time don't need that,
- this allows me decouple implementation details of classes interface, want.
example:
struct { const int& value(const std::size_t i) const { return values_[i]; } int& value(const std::size_t i) { return values_[i]; } private: std::vector<int> values_; // storing values in vector/list/etc implementation detail. // - can validate index, not value :( // - can change type of values, without affecting clients :) };
now questions:
- are there other disadvantages of approach i'm failing see?
- why people prefer:
- getter/setters methods different names?
- passing value parameter? validating input or there other main reasons?
- generally using accessors/mutators @ design smell class public interface incomplete. typically speaking want useful public interface provides meaningful functionality rather get/set (which 1 or 2 steps better in c structs , functions). every time want write mutator, , many times want write accessor first take step , ask
"do *really* need this?"
. - just idiom-wise people may not prepared expect such function increase maintainer's time grok code.
- the same-named methods same public member: use public member in case. when methods 2 different things, name them 2 different things.
- the "mutator" returning non-const reference allow wide variety of aliasing problems stashes off alias member, relying on exist later. using separate setter function prevent people aliasing private data.
Comments
Post a Comment