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物件的用戶函式也無須改變。』
這下子終於清楚了解資料抽象和封裝的好處了,原來程式設計者也有分上中下游喔!我想我大概屬於下游的程式設計者,專作組合業的,可是這方面領域的人就多了,要嘛!就要作專業的上游,這樣比較有利潤可賺。