Summary

Practical guide on when to split functions vs. when not to, illustrated with a real React codebase example. Core insight: length alone is not a reliable indicator — over-splitting creates a “jumping between functions” readability problem worse than a long function.

關於何時拆分函數的實用指南,以 React 真實程式碼為例。核心見解:長度本身不是可靠的指標——過度拆分造成的「在函數間跳躍」可讀性問題可能比一個長函數更糟糕。

Key Points

  • Anti-pattern: splitting functions based on length alone — causes cognitive overhead from context-switching
  • When to split: (1) multiple responsibilities (name requires more than one verb, like “validateAndProcess”), (2) code reuse across multiple call sites, (3) testability of isolated logic
  • When NOT to split: when the resulting functions are too small/atomic to be independently meaningful; when the logic is inherently sequential and cohesive
  • Real-world trigger: author over-split a greedy algorithm during refactoring, making it harder to understand

Insights

The “name requires more than one verb” heuristic is immediately actionable — if you can’t name a function with a single clear verb phrase, it’s likely doing multiple things. The counter-argument to “always split small” is important: a function that exists in only one place and is not independently testable provides no value from extraction, only navigation overhead. The tension between “short functions = good” (Clean Code school) and “keep related logic together” (locality of behavior school) is the real debate underlying this article.

Connections

Raw Excerpt

If you’re trying to name a function and find yourself using more than one verb (e.g., validateAndProcessData), it’s a sign that the function is doing more than one thing.