开发者

Should property getters return values other than that of the private member?

private int _myField;
public int MyField
{
  get {
   return _myField * 99;
}
set {
   _myField * value;
}
}

I've seen developers add more complex code into the Getter, setting other members and properties etc. To me return a value other than the associated member variable causes debugging co开发者_如何学Cnfusion.

IS this better?

private int _myField;
public int MyField
{
  get {
   return _myField = _myField * 99;
}
set {
   _myField * value;
}
}

or this?

private int _myField;
public int MyField
{
  get {
   return _myField;
}
set {
   _myField = value * 99;
}
}


Neither of these are good. It's fine in some cases to set other members, perform caching, etc - there's no rule saying that a property has to just be backed by a member variable with no logic, after all, and validation is one very good example of where you'd want other logic.

However, it's usually not a good idea to write a property so that getting a value you've just set will give a radically different answer. In particular,

foo.SomeProperty = foo.SomeProperty;

should almost never do anything significant (whereas in your example it would change the value).

(Having said that, your setter code for the first two examples is broken.)


I think your second snippet is quite a violation of the code's semantics. Using a getter should not influence the public value - that is, you can do whatever you want inside the getter, such as caching or lazy initialisation and so on - but in the outside, two consecutive calls to the getter should return the same result.


Well, one of the reasons properties exist is so that you can do stuff just like this. Properties are a form of encapsulation that give you the ability to hide any logic that you need to hide from the caller.

My personal philosophy is that stuff like you have is fine (i.e. simple data manipulation that doesn't create side effects) but once the logic gets more complex than a few lines you should change over to a method to indicate to the caller that more is going on.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜