糟糕的编程风格,通过使用get访问器来更改对象的状态 [英] bad programming style to change the state of the object by using the get accessor
问题描述
您好
我怀疑为什么以下代码是错误的编程风格。它来自MSDN文档
使用
获取访问者。例如,每次访问
数字字段时,以下访问器都会产生更改对象状态的副作用。
这只是因为访问属性不应该改变对象的状态。 我应该能够重复获取一个属性并获得相同的答案。 它还使并发处理更加困难,因为你无法预测
可能首先得到哪个线程。
当然,每条规则都有例外。 如果你有一个提供唯一ID的对象,并且你记录了属性访问修改状态的事实,那么你当然可以这样做,尽管最好把它变成一个方法
而不是一个属性。
Hello
I had a doubt as to why the following code is a bad programming style . It is from MSDN Documentation
It is a bad programming style to change the state of the object by using the get accessor. For example, the following accessor produces the side effect of changing the state of the object every time that the number field is accessed.
It's just because accessing a property should not change the state of an object. I should be able to fetch a property repeatedly and get the same answer. It also makes concurrent processing more difficult, because you can't predict which thread might get in first.
There are exceptions to every rule, of course. If you have an object that is delivering a unique ID, and you document the fact that the property access modifies the state, then of course you can do it, although it might be better to make it a method instead of a property.
这篇关于糟糕的编程风格,通过使用get访问器来更改对象的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!