cleancode.in

Functions that do one thing

Clean ABAP puts numbers on a function: under 20 statements, best 3 to 5 source, and ideally fewer than three inputs source.

How big is a function?

  • ABAP: A method should do one thing, and only one thing. It should do it in the best way possible. source
  • ABAP: Methods should have less than 20 statements, optimal around 3 to 5 statements. source

How many inputs should it take?

  • ABAP: Aim for few IMPORTING parameters, at best less than three source
  • ABAP: Boolean input parameters are often an indicator that a method does two things instead of one. source

Can defaults replace overloads?

  • Kotlin: Prefer declaring functions with default parameter values to declaring overloaded functions. source

How many results should it give?

  • ABAP: A good method does one thing, and that should be reflected by the method also returning exactly one thing. source

Where do the checks go?

  • ABAP: Validate and fail as early as possible source

Why return early?

  • Go: The code reads well if the successful flow of control runs down the page, eliminating error cases as they arise. Since error cases tend to end in return statements, the resulting code needs no else statements. source

How does a function end?

  • PEP 8: Be consistent in return statements. Either all return statements in a function should return an expression, or none of them should. source

How short can a function be?

  • Kotlin: Prefer using an expression body for functions with the body consisting of a single expression. source
  • Rust: Prefer to use Rust’s expression oriented nature where possible; source

What does a tangled function look like?

Before, in Python
def process(order, send_mail):
    if order is not None:
        if order.items:
            total = 0
            for item in order.items:
                total = total + item.price * item.qty
            db.save(order, total)
            if send_mail:
                mailer.send(order.email, total)
            return total
        else:
            return
    else:
        raise ValueError("no order")

What does it look like cleaned up?

After
def order_total(order):
    return sum(item.price * item.qty for item in order.items)


def save_order(order):
    if order is None:
        raise ValueError("no order")
    if not order.items:
        return None
    total = order_total(order)
    db.save(order, total)
    return total


total = save_order(order)
if total is not None:
    mailer.send(order.email, total)

What changed?

  • One job each: order_total adds up, save_order saves. source
  • No send_mail flag: the caller sends the mail. source
  • Checks first, leaving at once: no else, no nesting. source source
  • Every return says what it returns, None too. source
  • order_total is one line: sum() replaces the loop.