getters and setters style

2019-02-07 20:44发布

(Leaving aside the question of should you have them at all.)

I have always preferred to just use function overloading to give you the same name for both getter and setters.

int rate() { return _rate; }      
void rate(int value) { _rate = value; }

// instead of     
int getRate() { return _rate; }      
void setRate(int value) { _rate = value; }

// mainly because it allows me to write the much cleaner     
total( period() * rate() );    
// instead of      
setTotal( getPeriod() * getRate() );

Naturally I am correct, but i wondered if the library writers had any good reason ?

13条回答
Emotional °昔
2楼-- · 2019-02-07 21:22

There are several levels to "Getting" and "Setting"

  • I use Get and Set for "fast" operations.
  • If something will take a longer time to execute, then it will often be a Calc, as these names imply that some work has to be done to retrieve the result.
  • For longer operations, you start to get into prefixes like Load/Save, Query/Store, Read/Write, Search/Find etc.

So Get/Set can be ascribed a useful meaning, and be part of a larger, consistent naming strategy.

查看更多
登录 后发表回答