Reputation: 2696
As the title says: Is it good practice to create functions to access class variables?
I have seen quite a number of pieces of code that do something like the following:
class MyClass {
public:
void setx(int a);
void sety(int b);
int read_x;
int read_y;
private:
int x;
int y;
};
void MyClass::setx(int a) {
x=a;
}
void MyClass::sety(int b) {
y = b;
}
int MyClass::read_x() {
return x;
{
int MyClass::read_y() {
return y;
}
So rather than accessing variables directly(MyClass.x) they use functions to read and set the variable values etc.
Is this a standard or good practice?
Upvotes: 2
Views: 539
Reputation: 16195
This is important as it separates the interface of the class from the underlying data model. You often see basic code like the example you posted, and at first, a lot of it can seem like an unnecessary complication. However, it provides a (self documenting) framework where the implmentation of the object can be changed without breaking code that accesses the objects of the class via the defined interface.
Upvotes: 1
Reputation: 442
Rather than access variables directly? Absolutely. Creating a programmatic interface layer decouples you from the implementation details of those internal variables themselves. You then afford yourself additional flexibility for things like creating mocked-out implementations of the class in question (for testing), creating proxy classes (for decorated functionality like logging, etc.)
I'd warn against automatically creating them for everything where you may not need them. But that's a different issue.
Much like working out at the gym: It gives back more than it takes ;)
Upvotes: 2
Reputation: 16148
Yes they are ok, however I would also say that you should keep your classes small than you would with say Java and what not so you don't end up with types that are mostly getters and setters.
Typically a class holds a (ideally single) state (which can be got if needed) and has an implementation which should ideally remain private.
Upvotes: 1
Reputation: 258588
Yes, accessor functions are preffered to direct member access for several reasons. They provide a unique access point, are easier to track and to debug.
For example, instead of setting a breakpoint everywhere in the code where MyClass.x
is changed, you can just set a single breakpoint in MyClass::setX()
.
However, although better than direct member access, accessor methods are not without their drawbacks, if misused. For details, you can visit Getters and Setters are bad OO design?
Upvotes: 4