When writing getter and setter methods in standard C++ there are three main approaches for naming.
1. Pure C++ method based on the references.
class Foo { Value field_; public: Value& field() { return field_; } const Value& field() const { return field_; } };
Usage:
Foo foo; foo.field() = field_instance; field_instance = foo.field();
Pros: brevity, closeness to the property notation and possibility of using in a cascade assignment (foo1.field() = foo2.field() = 2;
).
Cons: using the function call on the left looks unusual.
2. Java way
class Foo { Value field_; public: void setField(const Value& value) { field_ = value; } const Value& getField() const { return field_; } };
Usage:
Foo foo; foo.setField(field_instance); field_instance = foo.getField();
Pros: clarity and obviousness.
Cons: wordiness due to get
and set
prefixes.
3. Objective-C way
class Foo { Value field_; public: void setField(const Value& value) { field_ = value; } const Value& field() const { return field_; } };
Usage:
Foo foo; foo.setField(field_instance); field_instance = foo.field();
Pros: brevity (no useless get
prefix) and clarify.
Cons: haven’t found so far.
All three have rights to live but from the style perspective it’s good to be consistent and use only one style across one project.