Search code examples
c++oopencapsulationgetter-setter

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


Solution

  • 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());
    }