属性 getter 中的逻辑 [英] Logic in property getters
问题描述
对于属性 getter 来说,多少逻辑太多了?例如,我的代码如下所示:
How much logic is too much for a property getter? For example, I have code which looks like this:
public double value
{
get
{
if (condition1
|| condition2
|| condition3
|| condition4)
{
_value = anotherValue;
}
return _value;
}
}
我读过各种帖子,说属性中的代码不应该很昂贵.但是昂贵"这个词对我来说有点含糊.
I have read various posts that say the code inside properties should not be expensive. But the term 'expensive' is a bit vague for me.
推荐答案
一般来说,在 OOP 中,getter(setter)应该是一个微不足道的操作.您在上面发布的内容是微不足道的,取决于实际情况.
Generally speaking, in OOP a getter (setters too) should be a trivial operation. What you've posted above is trivial, depending on what the conditions actually are.
您提到昂贵"对您来说是一个模糊的术语.一个计算成本高的操作意味着它需要很长时间才能完成(通常是因为它必须完成大量的计算——这过于简单化了,但这是一个不错的近似值).例如,考虑:
You mentioned that "expensive" is a vague term to you. An operation being computationally expensive means that it will take a long time to complete (usually because it has to complete a lot of computations -- that's an oversimplification, but a decent approximation). For instance, consider:
if (a == 5
|| b == true
|| c == "FOO!"
|| d == 3.14159)
{
_value = anotherValue;
}
return _value;
在这个例子中,条件是微不足道的,你的程序将几乎瞬间处理这个块.另一方面:
In this example, the conditions are trivial, and your program will crunch through this block near-instantaneously. On the other hand:
if (some_slow_function())
{
_value = anotherValue;
}
return _value;
假设 some_slow_function 实际上运行很慢,这个块将需要很长时间才能返回 _value
,使其不再微不足道.如果这个 getter 被频繁调用,some_slow_function
也会被频繁调用,导致它成为你程序的瓶颈并导致它运行缓慢.
Assuming some_slow_function does actually run slowly, this block will take a long time to return _value
, making it no longer trivial. If this getter is called often, some_slow_function
will be called often as well, causing it to bottleneck your program and cause it to run slowly.
这篇关于属性 getter 中的逻辑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!