I always like to overthink things, so here's my thought of the day:
Should setters only set the values of class properties, and not perform any other logic?
Suppose I have a class
class User {
private:
int age;
bool is_alive;
public:
int GetAge();
void SetAge();
bool GetIsAlive();
void SetIsAlive();
};
When calling User::SetAge(5)
, one would assume that user.age == 5
. But what about User::GetIsAlive()
? Should setting the age of the user also perform internal logic to set the is_alive
property, or should that be up to the user of the class?
Should it only do exactly what the function says?
void User::SetAge(int age){
this->age = age;
}
or add additional operations?
void User::SetAge(int age){
this->age = age;
this->is_alive = (age < 100);
}
Should it be more explicit?
void User::DetermineIsAlive(){
this->is_alive = (age < 100);
}
Obviously this is a simple case, but in my real world examples, doing something like setting the enabled state of a class (Device.SetState(false)
) may then shut down sub components, update the status, etc..
I'm just curious if we think setters should ONLY set values or properties, and multi-statement functions should be more explicit in their naming.
is_alive
should be calculated, not stored, as in your last example.age
, as they would have to be manually updated everytime time changes (which is all the time).