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.』


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