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:
-
A general desire to avoid writing the same code in more than one place.
-
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.
-
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.
-
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()内部行为简单多少。为什么要这么做呢?有几个原因:
- 一般我们总是希望避免在一个以上的地方写出相同程式码。
- display()有可能随着class的扩展而更加复杂。随着其行为愈发复杂,显而易见地应该在单一地方(而不是两处或多处)撰写它们。
- 很有可能在开发过程中我们需要为do_display()加入除错资讯,这些资讯将在最终版本拿掉。如果只写一份do_display()定义式,添加和移除除错资讯会更容易些。
- 此函式呼叫并不消耗任何额外开销(overhead)。我们让do_display()成为inline,所以“呼叫do_display()”或“将程式码直接写进display()”,执行期效率其实相等。
现实生活中,设计良好的C++程式往往带有许多小函式–就像do_display()这样为其他函式作实际工作的小函式。’
我愈来愈了解小函式的意义了!