Siliproksi
Siliproksi

Reputation: 323

Should i use setters/getters in class I made them

Car.h

#ifndef CAR_H
#define CAR_H

class Car
{
     public:
        void setColor(int color);
        void colorCarWithRandomColor();
     private:
        int _color;            
};

#endif

Car.cpp

#include "Car.h"
void Car::setColor(int color){
   _color = color;
}
void Car::colorCarWithRandomColor(){
    // Imagine that there is a function called getRandomColor and that returns random color.
    _color = getRandomColor(); 
    // or
   setColor(getRandomColor());
   // which one is correct
}

So which one of these is better to use. _color = getRandomColor(); or setColor(getRandomColor()); in this case? Should i call setColor function or it is correct to directly change _col

Upvotes: 3

Views: 896

Answers (2)

Ðаn
Ðаn

Reputation: 10876

You should prefer to write code which will be as immune as possible to future changes, that generally means using your own setter (and getter) rather than directly accessing your own private data.

For example, say you decide to change _color to be an enum or an RGB-tuple. If you use _color directly, you'll have more places to change. Using setColor(int) you have just one place to convert from int to whatever your new internal storage might be.

Furthermore, in your particular example, since setColor is public, your colorCarWithRandomColor() method might be able to be a non-member non-friend function which further decreases coupling. (Of course, that depends on exactly how your getRandomColor() method works.)

void colorCarWithRandomColor(Car& car) {
    // Imagine that there is a function called getRandomColor and that returns random color.
   car.setColor(Car::getRandomColor());
}

Upvotes: 5

Quandon
Quandon

Reputation: 27

It's perfectly correct to directly refer to a variable within its own class.

The idea of accessors/mutators is that functions using the data outside the class should not make any assumptions about how it is stored.

Obviously the class itself knows how the data is stored so is free to manipulate it directly.

Upvotes: 2

Related Questions