Clean Code: Functions Explained by Robert C. Martin

Clean Code: Functions Explained by Robert C. Martin

What Is Clean Code?

Clean code is code that is easy to read, simple to maintain, and robust against bugs. Robert C. Martin, aka Uncle Bob, outlines essential practices in his book Clean Code: A Handbook of Agile Software Craftsmanship. This article focuses on his chapter about writing clean functions.

Top 10 Principles of Clean Functions

1. Functions Should Be Small

Small functions are easier to read and reuse. Ideally, each function should do just one thing and be a few lines long.

2. Do One Thing

A clean function should serve one purpose only. If you can describe it with "and", it's probably doing too much.

3. Use Meaningful Names

Your function name should clearly express what it does. Avoid vague or abbreviated names.

4. One Level of Abstraction

Don’t mix high-level and low-level logic in the same function. Keep it consistent and focused.

5. Minimize Arguments

Ideally, a function should take zero to two arguments. More than that? Consider grouping parameters into an object.

6. No Side Effects

Functions should not unexpectedly modify global state or class properties unless they are designed to do so.

7. Command-Query Separation

Functions should either perform an action (command) or return data (query)—not both.

8. Use Exceptions, Not Return Codes

Throw exceptions for errors rather than relying on boolean or numeric return codes.

9. Remove Duplicated Code

Duplicated code increases maintenance effort. Extract reusable logic into clean helper functions.

10. Prefer Polymorphism Over Conditionals

Replace long if/switch statements with polymorphism when working with different behaviors.

Bad vs Clean Function Examples

C# Example

❌ Bad Function


void ProcessUser(string name, int age, bool isAdmin) {
    if (isAdmin) {
        Console.WriteLine("Admin: " + name);
        // some admin logic
    } else {
        Console.WriteLine("User: " + name);
        // some user logic
    }
    if (age > 18) {
        Console.WriteLine("Adult");
    } else {
        Console.WriteLine("Minor");
    }
}
    

✅ Clean Function


void PrintUserRole(string name, bool isAdmin) {
    var role = isAdmin ? "Admin" : "User";
    Console.WriteLine($"{role}: {name}");
}

void PrintUserAgeCategory(int age) {
    Console.WriteLine(age > 18 ? "Adult" : "Minor");
}

void ProcessUser(string name, int age, bool isAdmin) {
    PrintUserRole(name, isAdmin);
    PrintUserAgeCategory(age);
}
    

JavaScript Example

❌ Messy Function


function calculate(data) {
  let tax = 0;
  if (data.country === "US") {
    tax = data.amount * 0.07;
  } else {
    tax = data.amount * 0.15;
  }
  console.log("Total: " + (data.amount + tax));
}
    

✅ Clean Function


function getTaxRate(country) {
  return country === "US" ? 0.07 : 0.15;
}

function calculateTotal(amount, taxRate) {
  return amount + amount * taxRate;
}

function displayTotal(data) {
  const rate = getTaxRate(data.country);
  const total = calculateTotal(data.amount, rate);
  console.log(`Total: $${total.toFixed(2)}`);
}
    

Why Clean Functions Matter

Clean functions improve readability, reduce bugs, and make collaboration easier. By following these principles, developers build code that lasts.

Final Thoughts

Robert C. Martin’s clean function guidelines are universal—use them in C#, JavaScript, Java, Python, or any other language. Keep functions small, purposeful, and expressive. Your future self and teammates will thank you.

Enjoyed this article? Share it with fellow developers and subscribe for more clean code tips!

Post a Comment

0 Comments