OO: Should you access your private variables throu

2019-05-05 05:43发布

I was wondering, what is good practice:

 private int value;

 public int Value { get { return this.value; } }

 private int DoSomething()
 {
      return this.Value + 1;
      //OR
      return this.value + 1;
 }

So, the question is about how you should treat your class variables. Should you access them through your properties or just direct?

8条回答
等我变得足够好
2楼-- · 2019-05-05 06:31

This is something that standards wars have been fought over. Usually it won't make a big difference and I settled on just accessing the variable directly from inside the class with the exception of getters and setters which do something beyond just getting or setting the value.

The catch is that you have to know what the getter and setting are doing, or you have to always limit them to the simple operation with no additional functionality.

查看更多
Deceive 欺骗
3楼-- · 2019-05-05 06:34

I vote for return this.value + 1.

The argument against this (ie going via the property) is that you might want to add extra code to your property method later, so there'd be less changes if you did that. But I'm of the mind that properties should just do as advertised and no more; that is, they should do just enough to return that value.

查看更多
登录 后发表回答