Reputation: 73
Say, we have a class that has internal state, implemented as a private variable and a method to determine that state. What is the oop-way to set the variable with a method:
class Car
{
..
private:
float speed_;
float calculate_optimal_speed();
..}
Is it better to make a function calculate_optimal_speed(), which returns the varible speed_ within its body or a void set_speed() method?
Say, we have a big method control_the_car(). What is preferred and will create less problem in the further development of the code:
float calculate_optimal_speed();
control_the_car()
{
..
speed_ = calculate_optimal_speed();
}
or
void set_optimal_speed();
control_the_car();
{
..
set_optimal_speed();
}
On one hand, implementing set_optimal_speed() allows to change the type of speed_ variable with less modifications of the code. On the other hand, returning a value allows to re-use the function if I need it again. Is there a rule of thumb here?
Upvotes: 0
Views: 121
Reputation: 2985
Having getters and setters can help you maintain and organize your code
class Car {
private:
// A private variable named speed_ of type float
float speed_;
float calculate_optimal_speed();
public:
// Constructor
Car(float x) { speed_ = x; }
// OR
Car(float speed_) { this->speed_ = speed_; }
// A getter for variable speed_ of type T receives no argument and return a value of type float
float getspeed_() const { return speed_; }
// A setter for variable speed_ of type float receives a parameter of type float and return void
void setspeed_(float x) { speed_ = x; }
// OR
void setspeed_(float speed_) { this->speed_ = speed_; }
}
control_the_car()
{
..
x = calculate_optimal_speed()
void setspeed_(float x) { speed_ = x; } ;
}
This way if you need to update speed variable you can use Setter to update it
Upvotes: 0
Reputation: 27375
Is there a rule of thumb here?
Yes: write the simplest implementation that covers your needs. If you need something different later, refactor.
This means you should probably use the set_optimal_speed();
implementation, unless you have speeds to calculate that do not need to be set in the private state of the class (if you do, make a function that returns the speed, then implement set_optimal_speed();
in terms of this function).
Upvotes: 1