When Should You Split a Function—and When Should You Keep It Together?
“Can we break this into smaller functions?” is an easy comment to leave on a pull request. It gives the implementer a clear action, and the revised diff will probably contain shorter functions. Whether the code becomes easier to understand is a separate question.
Take an order-submission workflow. It receives validated cart lines, groups them for fulfillment, constructs a request, and sends it to an order gateway. A reviewer wants the submission path to be easier to scan. Extracting every consecutive block would satisfy the comment, but it might also make the next reader jump between helpers to reconstruct one operation.
The design decision is where a reader should be able to stop. Can they trust a helper's input and result and continue reviewing submission, or must they read its neighbors to discover how it works?
We will refactor the same small TypeScript workflow in three ways: keep it together, extract one complete transformation, and split it into stages sharing mutable state. Comparing their reader obligations gives us a more useful extraction criterion than a line limit. It also tells us when combining fragments again is an improvement.
On this page
Begin With the Operation's Contract
For this example, the application has already validated the order input. These types define the work the review is about:
type CartLine = {
warehouseId: string
sku: string
quantity: number
}
type OrderInput = {
cartId: string
shippingAddressId: string
lines: readonly CartLine[]
}
type FulfillmentGroup = {
warehouseId: string
items: { sku: string; quantity: number }[]
}
type OrderRequest = {
cartId: string
shippingAddressId: string
fulfillment: FulfillmentGroup[]
}
type SubmittedOrder = { orderId: string }
type OrderGateway = {
submit(request: OrderRequest): Promise<SubmittedOrder>
}
Assume the identifiers are valid, each quantity is a positive safe integer, and aggregated quantities remain within that range. These are input preconditions; declaring quantity: number does not enforce them.
The operation groups quantities by warehouse and SKU, preserves the first occurrence order of warehouses and SKUs, and submits one request. The gateway is an abstract application dependency. Its persistence, inventory, and duplicate-submission semantics need their own contract; this example makes no guarantees about those mechanisms.
This is the behavior the refactoring must preserve. Without it, the review could reward shorter functions while missing a change in grouping or output order.
A Cohesive Function Can Be Read in Sections
Here is the function receiving that review comment:
async function submitOrder(
input: OrderInput,
gateway: OrderGateway,
): Promise<SubmittedOrder> {
const warehouses = new Map<string, Map<string, number>>()
for (const line of input.lines) {
let quantities = warehouses.get(line.warehouseId)
if (!quantities) {
quantities = new Map()
warehouses.set(line.warehouseId, quantities)
}
quantities.set(line.sku, (quantities.get(line.sku) ?? 0) + line.quantity)
}
const fulfillment = Array.from(warehouses, ([warehouseId, quantities]) => ({
warehouseId,
items: Array.from(quantities, ([sku, quantity]) => ({ sku, quantity })),
}))
return gateway.submit({
cartId: input.cartId,
shippingAddressId: input.shippingAddressId,
fulfillment,
})
}
There are several statements, but the flow is direct. Local variables belong to one invocation. The grouping is visible, and the submitted request follows it.
Keeping this function together is defensible if the grouping remains easy to understand and the surrounding workflow stays small. Its sequential nature does not automatically require a new abstraction for each stage.
The reviewer has still noticed a real cost. Someone checking which address and cart are submitted must pass through the grouping loop to reach the request. As grouping becomes more involved, it can obscure the submission decision. We have found a possible boundary: the transformation has a complete meaning that the surrounding workflow could rely on.
Extract a Subtask With a Complete Meaning
The grouping operation can stand on its own. It receives validated lines and returns fulfillment groups without sending a request or changing the input.
function buildFulfillmentGroups(
lines: readonly CartLine[],
): FulfillmentGroup[] {
const warehouses = new Map<string, Map<string, number>>()
for (const line of lines) {
let quantities = warehouses.get(line.warehouseId)
if (!quantities) {
quantities = new Map()
warehouses.set(line.warehouseId, quantities)
}
quantities.set(line.sku, (quantities.get(line.sku) ?? 0) + line.quantity)
}
return Array.from(warehouses, ([warehouseId, quantities]) => ({
warehouseId,
items: Array.from(quantities, ([sku, quantity]) => ({ sku, quantity })),
}))
}
The submission function now reads:
async function submitOrder(
input: OrderInput,
gateway: OrderGateway,
): Promise<SubmittedOrder> {
return gateway.submit({
cartId: input.cartId,
shippingAddressId: input.shippingAddressId,
fulfillment: buildFulfillmentGroups(input.lines),
})
}
Now return to the pull request. The reviewer checking submission can read the cart, address, and fulfillment fields directly. If grouping is outside the change, its contract is enough. A reviewer checking grouping can open that function without learning the gateway or shipping-address fields.
The new function answers a complete question: given these lines, what fulfillment groups do they describe? Its inputs and output explain that question. It does not require a previous call to initialize hidden state or a later call to finish constructing its result.
A useful extracted subtask lets the parent and child remain understandable without reading each other's implementation. A second caller is not necessary to establish that benefit. A clear contract and an independently understandable calculation are already useful.
The contract also provides meaningful verification cases. Lines from different warehouses stay in separate groups. Repeated SKUs within one warehouse have summed quantities. The same SKU in another warehouse remains separate. Input order and contents remain unchanged.
Those cases check the transformation's behavior. They are more informative than checking whether submitOrder called three helpers in a prescribed order.
Fragmenting the Workflow Can Create a Hidden Protocol
A second response to the same review comment extracts every stage. The helpers communicate through a shared object:
type SubmissionContext = {
input: OrderInput
fulfillment?: FulfillmentGroup[]
request?: OrderRequest
result?: SubmittedOrder
}
declare function prepareFulfillment(context: SubmissionContext): void
declare function createRequest(context: SubmissionContext): void
declare function sendRequest(
context: SubmissionContext,
gateway: OrderGateway,
): Promise<void>
async function submitFragmented(
input: OrderInput,
gateway: OrderGateway,
): Promise<SubmittedOrder> {
const context: SubmissionContext = { input }
prepareFulfillment(context)
createRequest(context)
await sendRequest(context, gateway)
return context.result!
}
The declared helpers represent a deliberately awkward design: each reads fields installed by its predecessor and writes fields needed by its successor. Their implementations are omitted because the problem is the communication contract.
The revised submission looks easy to scan until the reviewer asks whether createRequest can run safely. They must open prepareFulfillment to discover which fields it installs, then inspect the later stages to see what must happen next. The signatures all say SubmissionContext; none explains the state transition it requires. The non-null assertion at the end hides an ordering assumption from the type checker rather than proving it.
Changing a stage can require reading all the other stages. Calling createRequest independently is not meaningful unless someone knows how to prepare its context first.
These fragments remain tightly coupled through their shared context. Separating them physically has not separated the knowledge needed to understand them.
An explicit state model can be appropriate for a workflow whose stages are genuinely resumable or independently operated. This simple operation has no such requirement. Adding more types to formalize accidental stages would need a benefit beyond preserving the extraction.
For this example, keep the grouping transformation and return to one visible submission flow. The caller should not have to operate an internal protocol just to submit an order.
Combining Can Remove Interfaces, Not Just Files
Joining related code is useful when the join eliminates knowledge or coordination that currently crosses a boundary.
Several reasons can justify combining code: shared information, a simpler resulting interface, and the removal of genuine duplication. The benefit comes from the new arrangement, rather than from having fewer files as a goal in itself.
In the fragmented submission, combining request construction and sending means callers no longer pass a partially initialized context between helpers. An intermediate mutable representation disappears. The complete operation has one input and one eventual result.
Shared information is another signal. Two helpers that each understand exactly which fulfillment fields must be installed before submission have overlapping knowledge of the same internal protocol. Bringing the work together can make that relationship explicit and local.
However, being used together in one direction does not always justify a merge. An order workflow uses grouping, but grouping can be understood without order submission. The transformation need not acquire a gateway dependency just because its current caller has one.
That asymmetry is valuable evidence for keeping the extracted function separate.
Separate a Mechanism From the Policy That Uses It
Some splits are useful because the two pieces answer different questions.
A general collection operation can group values by a key. A fulfillment policy decides which key matters, which quantities can be combined, and what output order the application promises. Sharing a grouping mechanism does not require putting every business rule into that mechanism.
Equally, two pieces of code can look similar while representing different policies. Fulfillment grouping and an analytics report might both accumulate records in a map. That similarity invites investigation, but it does not establish that their grouping rules should change together.
This is design reasoning applied to the example, rather than a rule against deduplication. A small, well-defined shared mechanism can be worthwhile. A universal buildGroups function with mode flags for unrelated business operations may instead couple decisions that should remain independent.
For the current workflow, buildFulfillmentGroups deliberately names the domain transformation it performs. There is no need to manufacture a generic grouping framework to justify extracting it.
Treat Function Length as a Clue
Extracting code solely to meet a function-length threshold can introduce interfaces and coordination without providing a useful abstraction. Judge the boundary by the responsibility it separates and the work it leaves to callers.
A short conversion can have an excellent contract. A long routine can bury unrelated responsibilities. A compact function can also be hard to understand if its few lines depend on a large amount of implicit state.
Length can prompt a review. The review still needs to identify the actual difficulty: too many responsibilities, excessive nesting, hidden dependencies, an independent calculation, or a protocol scattered across helpers.
For the order workflow, keep buildFulfillmentGroups as a complete transformation and let submitOrder assemble and submit the request visibly. The shared-context stages add an ordering protocol that this operation does not need, so combine them again.
In the next refactoring review, name the proposed helper's question, inputs, result, and assumptions before extracting it. Check whether the caller can continue without opening the helper, and whether the helper makes sense without opening its caller. A useful split gives both readers somewhere to stop. When neither can stop, making the functions shorter has probably left the real work of understanding them unfinished.
