Skip to content
Velloreth
Programming 7 min read

Writing Clean Functions: Small, Focused, Testable

Clean functions do one thing, have clear names, and few parameters. Learn the rules, the trade-offs, and how to refactor messy functions.

By

What makes a function clean

A clean function is easy to name, easy to call correctly, and easy to test. Those three properties come from a small set of rules.

Do one thing

The central rule. A function should do one thing, at one level of abstraction.

// Does several things
function processOrder(order: Order) {
  // validate
  if (!order.items.length) throw new Error('Empty order');
  if (order.total < 0) throw new Error('Negative total');

  // calculate
  let tax = 0;
  for (const item of order.items) tax += item.price * 0.13;

  // persist
  db.insert('orders', { ...order, tax });

  // notify
  email.send(order.customerEmail, 'Order confirmed');
}

This function validates, calculates, persists, and notifies. Four reasons to change. Four things to test.

// Each does one thing
function validateOrder(order: Order): void {
  if (!order.items.length) throw new Error('Empty order');
  if (order.total < 0) throw new Error('Negative total');
}

function calculateTax(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price * TAX_RATE, 0);
}

async function placeOrder(order: Order): Promise<void> {
  validateOrder(order);
  const tax = calculateTax(order.items);
  await orderRepository.save({ ...order, tax });
  await emailService.sendConfirmation(order);
}

placeOrder now reads as a sequence of named steps. Each step is independently testable. Each has one reason to change.

The test for “one thing”

Can you describe what the function does without using “and”? If not, it does more than one thing.

placeOrder — “places an order”. One thing. processOrder — “validates and calculates and saves and notifies”. Four things.

One level of abstraction

A function should not mix high-level policy with low-level detail.

// Mixed levels
function generateReport(users: User[]) {
  const rows = users.map((u) => `${u.name},${u.email}`);
  const csv = rows.join('\n');
  const buffer = Buffer.from(csv, 'utf8');
  const compressed = zlib.gzipSync(buffer);
  fs.writeFileSync('report.csv.gz', compressed);
}

The function talks about users and reports, then about buffers and gzip. The low-level part should be extracted:

function generateReport(users: User[]) {
  const csv = toCsv(users);
  writeCompressed('report.csv.gz', csv);
}

function toCsv(users: User[]): string {
  return users.map((u) => `${u.name},${u.email}`).join('\n');
}

function writeCompressed(path: string, content: string): void {
  fs.writeFileSync(path, zlib.gzipSync(Buffer.from(content, 'utf8')));
}

Now generateReport reads at one level: build the CSV, write it compressed. The details live in their own functions.

Few parameters

Fewer parameters make a function easier to call correctly.

// Easy to get the order wrong
function createUser(name: string, email: string, age: number, country: string, plan: string) { }

createUser('Ada', 'ada@example.com', 36, 'UK', 'pro'); // which is which?
// A parameter object names each field
interface CreateUserInput {
  name: string;
  email: string;
  age: number;
  country: string;
  plan: string;
}

function createUser(input: CreateUserInput) { }

createUser({ name: 'Ada', email: 'ada@example.com', age: 36, country: 'UK', plan: 'pro' });

The call site is now self-documenting, and adding a field does not change the signature.

Flag arguments

A boolean parameter that switches behaviour hides two functions in one.

// Bad: what does true mean?
render(data, true);

// Good: two named functions
renderWithHeader(data);
renderWithoutHeader(data);

The call site render(data, true) tells the reader nothing. Splitting it makes the intent explicit.

Return or mutate, not both

A function should either return a value or cause a side effect, not both.

// Surprising: returns a value AND writes to the database
function getUser(id: string): User {
  const user = db.find(id);
  db.incrementViewCount(id); // hidden side effect
  return user;
}

A caller who just wants to read the user has now changed the database. The name getUser implies a read.

// Clear separation
function getUser(id: string): User {
  return db.find(id);
}

function recordUserView(id: string): void {
  db.incrementViewCount(id);
}

The command-query separation principle: a function either answers a question or performs an action, not both.

Naming

A good function name makes the body almost redundant.

// The name says it all
function isEligibleForDiscount(user: User, cart: Cart): boolean {
  return user.isPremium && cart.total > 100;
}

Use verbs for actions, predicates for booleans, and be specific. Avoid handle, process, and manage, which do not say what happens.

Short functions

Short functions are easier to name, test, and reuse. The name becomes the documentation.

// Long and hard to name
function updateUserAndNotify(userId, data) {
  // 60 lines
}

// Short and clearly named
function updateUser(userId: string, data: UserUpdate): Promise<User> { }
function notifyUserUpdated(user: User): Promise<void> { }

The practical guideline is under 20 lines, but the real test is whether the function does one thing. A 30-line function that does one thing is fine; a 10-line function that does three is not.

Refactoring a messy function

The process is mechanical.

1. Identify the blocks. Read the function and find the natural sections — usually marked by comments or blank lines.

2. Extract each block into a function with a name describing what it does.

3. Replace the block with a call to the extracted function.

4. Repeat until the original reads as a sequence of named steps.

5. Test after each extraction.

// Before
function handleRequest(req) {
  // parse
  const body = JSON.parse(req.body);
  // validate
  if (!body.email) throw new Error('Email required');
  if (!body.email.includes('@')) throw new Error('Invalid email');
  // save
  db.insert('users', body);
  // respond
  return { status: 201, body: { id: body.id } };
}

// After
function handleRequest(req) {
  const body = parseBody(req);
  validateUserInput(body);
  const user = saveUser(body);
  return created(user);
}

The refactored version reads as a sequence of steps, and each step is testable.

The limits

Over-extraction is a real problem. A function split into ten one-line helpers is harder to follow than the original, because the reader must jump between definitions.

The signals of over-extraction:

  • Functions with one line that are called once.
  • Names that are harder to understand than the code they replace.
  • A file with fifty tiny functions and no clear structure.
  • Helpers that exist only to satisfy a line-count rule.

The judgement: extract when it improves clarity. A named step is clearer than an inline block when the block has a clear purpose. If the extraction adds a name without adding meaning, leave it inline.

Functions and testability

There is a direct relationship between how a function is written and how easy it is to test, and it is worth making explicit because it is the practical payoff of everything above.

A function that does one thing is easy to test, because there is one behaviour to verify. A function that does four things needs four tests, and each one must set up the state for the other three.

A function with few parameters is easy to call in a test. A function with six parameters needs six values, most of which are irrelevant to the case under test.

A function that returns a value is easy to assert on. A function that mutates global state requires inspecting that state afterwards, which couples the test to the implementation.

// Hard to test: does four things, mutates, returns nothing
function processOrder(order) {
  validate(order);
  const tax = calculateTax(order);
  db.save({ ...order, tax });
  email.send(order.email);
}

// Easy to test: pure, one thing, returns a value
function calculateTax(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price * TAX_RATE, 0);
}

The second function needs no setup, no mocks, and no teardown. You pass an array and assert a number. That is the shape to aim for, and it is why the rules about doing one thing and returning rather than mutating are not just aesthetic.

Practical guidance

  • Do one thing — if you need “and” to describe it, split it.
  • Keep one level of abstraction per function.
  • Use at most three parameters; beyond that, use an object.
  • Avoid flag arguments — split into two functions.
  • Return or mutate, not both.
  • Name functions so the body is almost redundant.
  • Extract until it reads as named steps, then stop.
  • Test after each extraction.

For the related practices, see naming conventions guide and when to write code comments. For the broader context, refactoring basics and pure functions and side effects.

Quotable summary

A clean function does one thing at one level of abstraction, which means it has one reason to change and does not mix high-level policy with low-level detail. Fewer parameters make a function easier to call correctly, and more than three usually signals a missing concept that belongs in a parameter object. Functions should either return a value or cause a side effect, not both, so callers know what to expect. Short functions are easier to name, test, and reuse, and the name becomes the documentation. Extract until the function reads as a sequence of well-named steps, then stop — over-extraction produces a maze of one-line helpers that is harder to follow than the original.

Frequently asked questions

How long should a function be?
There is no hard limit, but most clean functions are under 20 lines. The better test is whether it does one thing at one level of abstraction. If you need a comment to explain a block, extract it.
How many parameters is too many?
More than three is a warning sign. Four or more usually means the parameters belong together in an object, or the function is doing several things. A parameter object also makes call sites readable.
What does 'one level of abstraction' mean?
A function should not mix high-level policy with low-level detail. If it calls a service and also manipulates string indices, the two levels are mixed and the low-level part should be extracted.
Should a function have side effects?
It can, but it should be obvious from the name. A function called getUser should not also write to a database. Mixing a return value with a hidden side effect surprises callers.
Is it bad to have many small functions?
Not inherently, but over-extraction produces a maze of one-line functions that is harder to follow than the original. Extract when it improves clarity, not to hit a line count.
What is a flag argument?
A boolean parameter that switches behaviour, like render(data, true). It hides two functions in one and makes call sites unreadable. Split it into two named functions instead.