getter和setters样式 [英] getters and setters style
问题描述
我总是倾向于使用函数重载给你同样的名字为getter
int rate(){return _rate; }
void rate(int value){_rate = value; }
//而不是
int getRate(){return _rate; }
void setRate(int value){_rate = value; }
//主要是因为它允许我写出更干净的
total(period()* rate());
//而不是
setTotal(getPeriod()* getRate());
自然我是正确的,但我想知道图书馆作家是否有什么好的理由?
我更喜欢get / set版本,因为它更清楚什么是发生了。如果我看到rate()和rate(10),我怎么知道rate(10)不是简单地使用10在计算中返回率?我不,所以现在我不得不开始搜索找出发生了什么。单个函数名应该做一件事,而不是两个相反的事情。
另外,正如其他人所指出的,有些人喜欢省略get ',即
int Rate();
void SetRate(int value);
这个约定也很清楚,我不会有任何问题。 >
(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 ?
I would prefer the get/set versions because it is more clear as to what is going on. If I saw rate() and rate(10), how do I know that rate(10) isn't simply using 10 in the calculation to return the rate? I don't, so now I have to start searching to figure out what is going on. A single function name should do one thing, not two opposing things.
Also, as others have pointed out, some prefer to omit the 'get' and leave the 'set', i.e.,
int Rate( );
void SetRate( int value );
That convention is pretty clear as well, I wouldn't have any problem reading that.
这篇关于getter和setters样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!