NewsCrawler.org

Rule of thumb: avoid public functions calling other public functions

A blog post argues that when a public function foo reuses behavior already handled by another public function bar, the DRY[1] instinct to call bar() from within foo usually creates problems down the line. Instead, the author recommends extracting a new private function and refactoring both foo and bar to call that shared helper. The rationale is that a public API should work best at the call site, and reusing parts of the API to implement the rest creates tension between convenience for outside users and convenience inside the abstraction. Under that pressure, functions tend to grow optional parameters that users should never set, and this growth and interface degradation can begin after the original code sharing was introduced. Making the shared implementation private defuses the tension, because changes to a private helper's signature are cheap, local edits.

The one named exception is 'shortcut' APIs, where a public function is defined as a commonly used chain of calls to other public functions; there the rule is reversed and no private calls are allowed, so the function stays a genuine shortcut rather than a midlayer mistake[2].

The author also cites a Stack Overflow question on this practice, where the most upvoted answer calls it bad because it complicates mocking[3] a single method in isolation. That consequence is rejected as a result of a misguided approach to testing: developers should mock their IO rather than their methods, and test software functionality rather than individual methods, unless they are building a public library with a stable API. The accepted answer, that the recommendation makes no sense without an industry-wide or organizational standard, is also dismissed — guidelines concentrate good reasoning, but they don't absolve anyone from thinking, and rules should be applied for the underlying reasons that motivate them.

Read the original matklad.github.ioDiscussion

Discussion

Commenters mostly engage with the proposed fix: one asks why foo and bar shouldn't each call their own private helper, since a shared helper switched by flags would just trade a flag boolean for a flag enum, and the answer depends on how much code the helpers would share. Another recalls that some of the worst APIs grow by adding optional function after optional function to keep "everything in one function call", which effectively reinvents multiple functions through parameters.

Sources

Published: First seen: Читать по-русски

Open as a page