hn.today

Avoid Public Functions Calling Other Public Functions

matklad.github.io3 points2 comments
Screenshot of Avoid Public Functions Calling Other Public Functions

When one public function partly repeats another’s work, the instinct to avoid duplication is to implement the first by calling the second. The recommendation is instead to extract their shared behavior into a private helper and have both public functions call it. Public APIs should be designed for callers outside the module, while internal implementation may need different controls or parameters. If public functions depend on one another, internal needs can gradually add options that ordinary users should not have to see, making the API less convenient. A private helper keeps that complexity local and makes its signature easier to change without affecting callers.

The rule has a specific exception: a “shortcut” API intentionally packages a commonly used sequence of public calls. Such a function should use those public calls, rather than bypassing them through private helpers, so it remains a genuine shortcut rather than an awkward extra layer. The argument is not that public-to-public calls are inherently harmful because they complicate mocking; mocking methods to test them in isolation is itself criticized. Tests should generally focus on software behavior and mock external input/output, not internal methods. Nor should design rules be followed merely because an organization or industry endorses them. The point is to understand the practical reasons behind a guideline and apply it where those reasons matter.

Read on matklad.github.io2 comments on Hacker News

Summary generated by AI from the linked article. hn.today is not affiliated with Hacker News or Y Combinator.

More in Programming

The daily digest

Today's best Hacker News stories, summarized and screenshotted, one email a day.