在我们上一篇用的例子CircleCount中使用的r跟count,这两个数据域我们可以直接通过C.count=6, C.r=-10等这样类似的形式对其进行修改,这是非常不好的。因为:
■ First, data may be tampered with. For example, numberOfObjects is to count the
number of objects created, but it may be mistakenly set to an arbitrary value (e.g.,
Circle2.numberOfObjects = 10).
■ Second, the class becomes difficult to maintain and vulnerable to bugs. Suppose you
want to modify the Circle2 class to ensure that the radius is nonnegative after other
programs have already used the class. You have to change not only the Circle2
class but also the programs that use it, because the clients may have modified the
radius directly (e.g., myCircle.radius = -5)
也就是
1) 数据可能被恶意修改,例如我们count是用来计算创建的对象的个数,但现在我们可以直接修改它。
2)不利于我们维护及容易出现bug,因为像我们可能在外面直接令 C.r=-23等这样的负数,每次我们回去使用我们的对象时候,我们必须检查我们的r是不是还是正数的,但是如果我们能够