开发者

Being observable

What does it mean: Object's observable state?

I was reading yesterday in "Exceptional C++" Solution to item 43 and there is a fragment:

private: void InvalidateArea() { area = -1; }

Even though this function modifies the object's internal state, it should be const. Why? Because this function does not modify the object's observable state. We are doing some caching here, but that's an internal implementation detail and the object is logically const even if it isn't physically const.

Corollary: The member variable area shoul开发者_如何学JAVAd be declared mutable. If your compiler doesn't support mutable yet, kludge this with a const_cast of area_ and write a comment telling the next person to remove the const_cast once mutable is available—but do make the function const._

As usual thanks for answers.


Observable state means the state of the object that can be observed by an external object. Internal caching only changes the private state of the object, but it doesn't make any observable difference to users of the object (except for non-functional matters like speed of access).


In this context, "observable state" means whether something is, directly or indirectly, visible to users of the object.
If using code can not, through observing the return value of any accessible member function or the value of any accessible data member, tell a difference between the object having one value of area or another, than area is not part of the object's observable state.
If, OTOH, using code could, for example, call a member function, and that function's result would differ depending on the value of area, then area would be part of the object's observable state.


This means that state variable is not available for client code directly or through get function. From client point of view, class instance is not changed.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜