Index of every page on this site: llms.txt
All skills
jd-solanki avatar

/clean-code

@372cfb1
by JD Solankijd-solanki/ai6 stars
2
Run it yourself

Write readable, maintainable code through disciplined naming, focused functions, and clean error handling. Use when the user mentions "code review", "naming conventions", "function too long", "code smells", "readable code", "boy scout rule", "single responsibility", or "unit test quality". Also trigger when reviewing pull requests for readability, refactoring messy functions, debating comment styles, or improving error handling patterns. Covers SRP, comment discipline, formatting, and unit testing. For refactoring techniques, see refactoring-patterns. For architecture, see clean-architecture.

Use this Skill: https://skilld.dev/gh/jd-solanki/ai/clean-code

Nothing lands on disk. Nothing to clean up.

Fork this Skill

Edit a local copy. It keeps the author and licence.

referencesfunctions-and-methods.md

≈3.2k tokens on demand. Your agent reads this file only when SKILL.md points to it.

Functions and Methods

Comprehensive guide to writing focused functions that do one thing well. Based on Robert C. Martin's Clean Code, Chapters 3 and 4.

Table of Contents

  1. The First Rule of Functions
  2. Do One Thing
  3. Function Arguments
  4. Flag Arguments
  5. Command-Query Separation
  6. Side Effects
  7. Extraction
  8. Structured Programming
  9. DRY: Don't Repeat Yourself
  10. Function Organization Within a Class
  11. Common Function Anti-Patterns

The First Rule of Functions

Functions should do one thing. Size follows from that: length is a reason to look for a second job, not a limit to cut to. A long function with one job behind a small signature beats the same job scattered across helpers the reader must hop between.

A well-written function:

  • Has a name that describes exactly what it does
  • Takes few arguments (zero is best, three is the maximum)
  • Has no side effects
  • Operates at a single level of abstraction

Do One Thing

Functions should do one thing. They should do it well. They should do it only.

How to Know if a Function Does One Thing

If you can extract another function from it with a name that is not merely a restatement of its implementation, the function does more than one thing.

# BAD: Does three things
def process_payment(order):
    # 1. Validate
    if not order.items:
        raise ValueError("Empty order")
    if order.total <= 0:
        raise ValueError("Invalid total")

    # 2. Charge
    payment_result = gateway.charge(order.customer.card, order.total)
    if not payment_result.success:
        raise PaymentError(payment_result.error)

    # 3. Notify
    email_service.send_receipt(order.customer.email, order)
    analytics.track("payment_completed", order.id)

# GOOD: Does one thing, delegates details
def process_payment(order):
    validate_order(order)
    charge_customer(order)
    send_notifications(order)

The Step-Down Rule

Code should read like a top-down narrative. Every function should be followed by the next level of abstraction.

To process a payment:
    We validate the order.
    We charge the customer.
    We send notifications.

To validate the order:
    We check it has items.
    We check the total is positive.

To charge the customer:
    We call the payment gateway.
    We handle any payment failure.

To send notifications:
    We email the receipt.
    We track the analytics event.

This reads like a newspaper: the headline (top-level function) tells you the story, and each successive paragraph (sub-function) provides more detail.


Function Arguments

The ideal number of arguments for a function is zero (niladic). Next comes one (monadic), followed closely by two (dyadic). Three arguments (triadic) should be avoided where possible. More than three (polyadic) requires very special justification.

Argument Count Guide

Count Name When acceptable Example
0 Niladic Simple operations getCurrentTime()
1 Monadic Asking a question or transforming input isValid(email), parse(json)
2 Dyadic Natural pairings Point(x, y), assertEquals(expected, actual)
3 Triadic Rarely; consider object Color(r, g, b)
4+ Polyadic Almost never Wrap in object: new Config(...)

Common Monadic Forms

Three common reasons to pass a single argument:

  1. Asking a question: boolean fileExists(path) -- returns true/false about the argument
  2. Transforming it: InputStream fileOpen(path) -- transforms the argument and returns the result
  3. Event: void passwordAttemptFailedNTimes(attempts) -- uses the argument to alter system state (make this clear from the name)

Why Many Arguments Are Problematic

// BAD: What does each argument mean? What order?
createReport(title, startDate, endDate, format, includeCharts, sendEmail, recipients);

// GOOD: Parameter object groups related arguments
ReportConfig config = new ReportConfig.Builder()
    .title("Q4 Revenue")
    .dateRange(startDate, endDate)
    .format(PDF)
    .includeCharts(true)
    .build();
createReport(config);

Each argument increases the difficulty of understanding, testing, and calling the function. Arguments also create ordering dependencies that the reader must memorize.


Flag Arguments

Flag arguments are ugly. Passing a boolean into a function loudly declares that the function does two things -- one thing if the flag is true, another if false.

# BAD: Flag argument
def render(document, is_for_print):
    if is_for_print:
        # 20 lines of print rendering
        ...
    else:
        # 20 lines of screen rendering
        ...

# GOOD: Two clearly named functions
def render_for_print(document):
    ...

def render_for_screen(document):
    ...

If a function must behave differently based on a condition, split it into two named functions. If the behaviors share logic, extract the shared part into a private helper.


Command-Query Separation

Functions should either do something (command) or answer something (query), but not both.

// BAD: Does this set the attribute or check if it exists?
if (set("username", "unclebob")) { ... }

// GOOD: Separate query from command
if (attributeExists("username")) {
    setAttribute("username", "unclebob");
}

Commands change the state of an object. They should return void. Queries return information about an object. They should not change state.

When a function both changes state and returns a value, the reader cannot tell from the call site what is happening.


Side Effects

A side effect is when a function promises to do one thing but also does other hidden things.

Common Hidden Side Effects

Declared purpose Hidden side effect Danger
checkPassword(user, password) Initializes a session Calling "check" unexpectedly logs user in
getUser(id) Creates user if not found "Get" implies read-only; caller doesn't expect writes
toString() Modifies internal state Debugging with print statements changes behavior
validate(input) Sends analytics event Validation during testing triggers real events

How to Fix Side Effects

  1. Make the side effect explicit in the name: checkPasswordAndInitSession()
  2. Separate the concerns: checkPassword() + initSession() as two calls
  3. Prefer option 2 -- separation makes testing easier and keeps functions honest

Extraction

Extract a block when it has its own name and its own job; the name then documents it, even if only one place calls it. An extraction that only renames a few lines, or whose callers must read its body to use it, adds a hop without hiding anything: leave it inline.

When to Extract

Signal Action
A block inside an if, else, for, or while Extract to named function
A comment explaining what the next lines do Replace comment with named function
A function you must scroll to follow Look for a second job to extract
Nested indentation deeper than 2 levels Extract inner blocks
Code that you'd need to re-read to understand Name it so you don't have to

Extraction Example

// BEFORE: Deeply nested, hard to follow
function processOrders(orders: Order[]) {
  for (const order of orders) {
    if (order.status === 'pending') {
      let total = 0;
      for (const item of order.items) {
        if (item.inStock) {
          total += item.price * item.quantity;
          if (item.quantity > 10) {
            total *= 0.9; // bulk discount
          }
        }
      }
      if (total > 0) {
        order.total = total;
        order.status = 'processed';
        db.save(order);
        emailService.sendConfirmation(order);
      }
    }
  }
}

// AFTER: Each function does one thing
function processOrders(orders: Order[]) {
  orders
    .filter(isPending)
    .forEach(processOrder);
}

function processOrder(order: Order) {
  const total = calculateOrderTotal(order);
  if (total > 0) {
    finalizeOrder(order, total);
  }
}

function calculateOrderTotal(order: Order): number {
  return order.items
    .filter(item => item.inStock)
    .reduce((sum, item) => sum + calculateItemPrice(item), 0);
}

function calculateItemPrice(item: Item): number {
  const basePrice = item.price * item.quantity;
  return item.quantity > BULK_DISCOUNT_THRESHOLD
    ? basePrice * BULK_DISCOUNT_RATE
    : basePrice;
}

function finalizeOrder(order: Order, total: number) {
  order.total = total;
  order.status = 'processed';
  db.save(order);
  emailService.sendConfirmation(order);
}

Structured Programming

Dijkstra's rule states that every function should have one entry and one exit: one return statement, no break or continue in loops, and never goto.

In practice, for small functions, multiple returns and early exits improve clarity:

# Guard clauses improve readability in small functions
def calculate_discount(customer):
    if customer is None:
        return 0
    if not customer.is_active:
        return 0
    if customer.total_purchases < MINIMUM_FOR_DISCOUNT:
        return 0

    return customer.total_purchases * DISCOUNT_RATE

Guard clauses handle the error cases at the top of the function, leaving the happy path unindented and clear. This pattern is preferable to deeply nested if-else chains.


DRY: Don't Repeat Yourself

Duplication is the root of all evil in software. Every piece of knowledge should have a single, unambiguous, authoritative representation in the system.

Types of Duplication

Type Example Fix
Exact duplication Same code block in three places Extract to shared function
Structural duplication Same algorithm with different data Template Method or Strategy pattern
Conceptual duplication Same business rule expressed differently Consolidate into single source of truth
Data duplication Same value computed in multiple places Compute once, pass result

The Rule of Three

The first time you write something, just write it. The second time you see duplication, note it. The third time, refactor. This avoids premature abstraction while still catching genuine duplication.


Function Organization Within a Class

The Newspaper Metaphor

Organize functions the way a newspaper organizes articles:

  1. Headline at the top: Public methods (the API) appear first
  2. Synopsis next: High-level private methods called by the public methods
  3. Details last: Low-level helper functions at the bottom

The reader can stop reading at any depth once they have enough understanding.

Vertical Distance

Dependent functions should be close. If one function calls another, they should be vertically close in the source file, and the caller should be above the callee.

// GOOD: Caller above callee, close together
public void processOrder(Order order) {
    validateOrder(order);
    chargeCustomer(order);
    shipOrder(order);
}

private void validateOrder(Order order) {
    // validation logic
}

private void chargeCustomer(Order order) {
    // payment logic
}

private void shipOrder(Order order) {
    // shipping logic
}

Variables should be declared as close to their usage as possible. Local variables at the top of the function. Loop variables inside the loop statement. Instance variables at the top of the class (everyone needs to know they exist).


Common Function Anti-Patterns

Anti-pattern Problem Refactoring
Output arguments appendFooter(report) -- is report input or output? Make it a method: report.appendFooter()
Selector arguments calculate(MONTHLY) enum switches behavior Split: calculateMonthly(), calculateAnnual()
Dead functions Never called, just sitting there Delete them. Version control remembers.
Switch statements Long switches violate SRP and OCP Replace with polymorphism or strategy pattern
Temporal coupling Functions must be called in a specific order Make ordering explicit through return values or builder
Leaky abstraction Function exposes implementation details Hide internals, return domain objects

Source: SKILL.md on GitHub

No rule matched.

skilld matched fixed text patterns in SKILL.md and file names. Patterns miss obfuscated code.

skilld run checks every file with the same patterns. It asks for approval before it loads a Skill with a behavior marked Needs approval.

No alerts1mo3 checks · Risk SAFE
  • Gen Agent Trust Hub1mo

    The skill provides a comprehensive framework for writing clean code based on established industry principles. It consists entirely of instructional markdown documentation and does not contain executable code, scripts, or security risks.

  • Socket1mo

    No alerts

  • Snyk1mo

    Risk: LOW · No issues

Signed by skilld at 372cfb1. This ties the file your Agent reads to that commit on GitHub. It does not review the instructions.

Last checked against GitHub 4 days ago.

Activeupdated last month
Other metadata
metadata
{
  "credits": {
    "skill": "clean-code",
    "author": "Michal Jaskolski",
    "organisation": "Wondelai",
    "url": "https://github.com/wondelai/skills/blob/main/clean-code/SKILL.md",
    "ref": "968c8716fae05819b5dd40b2327952572ee50fff"
  }
}

README badge

README badge for jd-solanki/ai/clean-code