比如说,我们有一个具有内部状态的类,作为私有变量实现的类和确定该状态的方法。用方法设置变量的oop方法是什么:
class Car
{
..
private:
float speed_;
float calculate_optimal_speed();
..}让一个函数calculate_optimal_speed()返回其体内的varible speed_还是一个void set_speed()方法更好呢?
比如说,我们有一个很大的方法control_the_car()。在代码的进一步开发中,哪些是首选的,并将减少问题:
float calculate_optimal_speed();
control_the_car()
{
..
speed_ = calculate_optimal_speed();
}或
void set_optimal_speed();
control_the_car();
{
..
set_optimal_speed();
}一方面,实现set_optimal_speed()允许在代码修改较少的情况下更改speed_变量的类型。另一方面,返回一个值允许在我再次需要时重用该函数。这里有经验法则吗?
发布于 2014-07-02 11:38:41
这里有经验法则吗?
是的:编写最简单的实现来满足您的需求。如果你以后需要不同的东西,重构。
这意味着您可能应该使用set_optimal_speed();实现,除非您有不需要在类的私有状态下设置的速度(如果需要,则创建一个返回速度的函数,然后根据该函数实现set_optimal_speed(); )。
发布于 2014-07-02 11:53:06
拥有getter和setter可以帮助您维护和组织代码。
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; } ;
}这样,如果您需要更新速度变量,可以使用Setter更新它
https://stackoverflow.com/questions/24530009
复制相似问题