Functions - alexdaube/My-Software-Engineering-Guide GitHub Wiki

Functions

Rules

As Short as possible

  • Divide the code => Use small functions, private functions, don't use comments to explain easy stuff.
  • For readability and to code reuse
  • Code should be read like a story
  • Smells => Not fitting in a page, read twice to understand, vertical blocs...
public Paie genererPaie() {
    double salaireBrut = calculerSalaireBrut();
    double impot = calculerImpot(salaireBrut);
    double rrq = calculerRrq(salaireBrut + impot);
    double cumulatif = salaireBrut + impot + rrq;
    return new Paie(salaireBrut, impot, rrq, cumulatif);
}

private double calculerSalaireBrut() {
    double salaireBrut = 0;
    for(PlageHoraire plage: getPlagesHoraires())
        salaireBrut += plage.getHeures() * getTauxHoraire();
}

private double calculerImpot(double salaireBrut) {
    return salaireBrut * employe.getTauxImpot();
}
private calculerRrq(double cumulatif) {
    return cumulatif * getTauxRrq();
}

Should only do 1 thing

  • Shouldn't never be any and in the name of the function

One level of abstraction per function

  • Code should be readable in a descending manner. One abstraction level at a time.

Avoid multiple branching(switch cases)

  • Change the architecture instead. Factory, Polymorphism, tell don't ask, etc...

Don't use arguments to return

  • The less arguments, the better

Prefer calling methods than arguments in the constructor

  • watch out for inconsistency in how you create your objects.

Don't use flag arguments(boolean/condition)

  • Usually means the function will do more than one thing

Limit the number of arguments

  • Render tests more difficult to write

Prevent side effects

  • No surprise
  • If a method changes the state of the object. Should be evident.

Action or response

  • A function either execute an action or responds to a question, but not both
  • In Object Oriented, it should be an action most of time. Tell don't ask...

Never duplicate code

  • Especially if there is not unit tests
  • Don't have bugs emerged from copied and pasted code

Dry principle

  • Don't repeat yourself
  • 1 modification should not have an impact on what is not logically linked
  • Every piece of knowledge must have a single, unambiguous, authoritative representation within a system

OAOO Principles

  • Once And Only Once
  • Reuse to eliminate duplication
  • A design goal of eliminating duplicated declarations of behavior, typically by merging them or replacing multiple similar implementations with a unifying abstraction. Each and every declaration of behavior should appear OnceAndOnlyOnce. One of the main goals (if not the main goal) when ReFactoring code. Conceptually analogous to normalization in the RelationalModel