Benefits of Data Abstraction and Encapsulation

C++ Primer 4/e在Class Definitions and Declarations这个地方有一个关键观念:‘Data abstraction and encapsulation provide two important advantages:

  • Class internals are protected from inadvertent user-level errors, which might corrupt the state of the object.

  • The class implementation may evolve over time in response to changing requirements or bug reports without requiring change in user-level code.

By defining data members only in the private section of the class, the class author is free to make changes in the data. If the implementation changes, only the class code needs to be examined to see what affect the change may have. If data are public, then any function that directly accesses the data members of the old representation might be broken. It would be necessary to locate and rewrite all those portions of code that relied on the old representation before the program could be used again.

Similarly, if the internal state of the class is private, then changes to the member data can happen in only a limited number of places. The data is protected from mistakes that users might introduce. If there is a bug that corrupts the object’s state, the places to look for the bug are localized: When data are private, only a member function could be responsible for the error. The search for the mistake is limited, greatly easing the problems of maintenance and program correctness.

If the data are private and if the interface to the member functions does not change, then user functions that manipulate class objects require no change.’

中文版的这样写:‘资料抽象和封装,有两个重要优点:

  • Classes内部可以不受用户级(user-level)错误的影响,否则那些错误可能会破坏物件状态。
  • Classes的实作可以根据需求变化或错误回馈而不断改进,无须改变用户程式。

如果只在classes的private区段定义成员变数,classes作者就可以自由修改资料设计。万一classes的实作改变,也只需检查classes程式码,看看可能带来哪些影响。但如果资料是public,一旦修改设计,直接存取这些成员变数的程式都会遭到破坏。那么在这个程式能够被重新使用之前,必须先找出倚赖旧程式码的所有部份并予重写。

类似道理,如果classes的内部状态是private,那么成员变数的改变只会发生在很少几个地方。private资料不会受到用户引进的错误影响。如果有个程式错误地破坏了物件状态,出现错误的地点很容易被定位出来:当资料是private,只有成员函式才可能造成错误。搜寻这个错误很容易,维护和修改这个程式也很容易。

如果资料是private而成员函式的介面没改变,那么使用classes物件的用户函式也无须改变。’

这下子终于清楚了解资料抽象和封装的好处了,原来程式设计者也有分上中下游喔!我想我大概属于下游的程式设计者,专作组合业的,可是这方面领域的人就多了,要嘛!就要作专业的上游,这样比较有利润可赚。