Use Private Utility Functions for Common Code

C++ Primer 4/e在The Implicit this Pointer這個地方有一個關鍵觀念:『Some readers might be surprised that we bothered to define a separate do_display operation. After all, the calls to do_display aren’t much simpler than the action done inside do_display. Why bother? We do so for several reasons:

  1. A general desire to avoid writing the same code in more than one place.

  2. The display operation can be expected to become more complicated as our class evolves. As the actions involved become more complex, it makes more obvious sense to write those actions in one place, not two.

  3. It is likely that we might want to add debugging information to do_display during development that would be eliminated in the final product version of the code. It will be easier to do so if only one definition of do_display needs to be changed to add or remove the debugging code.

  4. There needn’t be any overhead involved in this extra function call. We made do_display inline, so the run-time performance between calling do_display or putting the code directly into the display operations should be identical.

In practice, well-designed C++ programs tend to have lots of small functions such as do_display that are called to do the “real” work of some other set of functions.』

中文版的這樣寫:『可能有些讀者會驚訝我們竟不厭其煩地多定意出一個do_display()。畢竟「呼叫do_display()」並不比do_display()內部行為簡單多少。為什麼要這麼做呢?有幾個原因:

  1. 一般我們總是希望避免在一個以上的地方寫出相同程式碼。
  2. display()有可能隨著class的擴展而更加複雜。隨著其行為愈發複雜,顯而易見地應該在單一地方(而不是兩處或多處)撰寫它們。
  3. 很有可能在開發過程中我們需要為do_display()加入除錯資訊,這些資訊將在最終版本拿掉。如果只寫一份do_display()定義式,添加和移除除錯資訊會更容易些。
  4. 此函式呼叫並不消耗任何額外開銷(overhead)。我們讓do_display()成為inline,所以「呼叫do_display()」或「將程式碼直接寫進display()」,執行期效率其實相等。

現實生活中,設計良好的C++程式往往帶有許多小函式–就像do_display()這樣為其他函式作實際工作的小函式。』

我愈來愈了解小函式的意義了!

感謝你看到這裡,很快就可以離開了,但最好的獎勵行動就是按一下幫我分享或留言,感恩喔~

點我分享到Facebook

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *