首頁 / CompScience / Programming / Languages / C_and_CPP / Use Private Utility Functions for Common Code

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()這樣為其他函式作實際工作的小函式。』

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

馬上成為工作達人的Fans

About ㄚ琪

工作達人Fun Taiwan的創辦者及總編,可以在這裡更認識他。

發表迴響

你的電子郵件位址並不會被公開。 Required fields are marked *

*

Scroll To Top

 好吃、好玩、旅遊、試吃、試用、邀稿、SEO

歡迎洽詢:flylinux@gmail.com

➨ 國外美食旅遊  日本東京自由行  美國猶他加州自由行  韓國釜山首爾慶州自由行 │ 泰國馬來西亞新加坡自由行  澳門廣東香港自由行日本九州奈良京阪自由行 │澳洲墨爾本坎培拉雪梨自由行 │中國北京自由行 

紅屋頂加級大阪難波飯店 (Red Roof Plus Osaka Namba) 日本大阪紅屋頂加級大阪難波飯店 (Red Roof Plus Osaka Namba)激推