Methods

Rules

  • "Small" - Not an exact rule

  • Do only one thing - even small methods may do more things!

  • One level of abstraction - See Law of Demeter later

  • No unexpected behavior (side effects)

  • No unexpected or not-understandable input and return values

  • No or the least possible dependencies

  • Avoid inline implementation - put it always in a separate method

  • Set visibility modifiers precisely - For the compiler and for the reader too

  • Check parameter validity at the beginning - Item 38 in Effective Java (2nd Edition, Joshua Bloch, 2008)

  • Prevent overriding non-abstract methods - Item 17 in Effective Java (2nd Edition, Joshua Bloch, 2008)

Example: Bad: Unexpected behavior

boolean checkPassword(String pwd) {
    if( pwd.equals(„secret”) ){
        createSession(); // Unexpected side effect
        return true;
    } else {
        return false;
    }
}

Example: Bad: Unintentional return values

Example: Bad: Method doing more than one thing

Example: Good: Methods doing one thing

Example: Bad: Method doing more than one thing (from the book)

Example: Good: Methods doing one thing (from the book)

Example: Bad: Side effect: modifying the input parameter

Avoid Bad Input Parameter Types

  • Object

  • String for non-textual types

  • boolean for switches - use constants or enum instead

Program to Methods

Stateless, independent methods:

  • Prefer return values to modifying input variables

  • Prefer methods that depend only on the input parameters -No configuration parameters or data mining inside

  • Independent = easily testable

At the end of the method calls there should always be a method that depend only on the input parameter and whose only result is the return value (or exception).

Overloading

  • Use overloading only for convenience

  • For example for default values

  • Do not use it for hiding differences

  • They should call each other - code smell if they don't

Hiding

  • Hide irrelevant details in a separate method

  • Do not hide relevant details in a separate method

Example: Bad: Overloads and Hiding

Example: Good: No overloads and Hiding

Two types of methods

  • "Coordinator" or "orchestrator"

  • "Technical" or "Algorithm"

Example: Good: Types of methods

How to use these types:

  • Do not mix business lines with technical lines

  • Do not pollute the code with technical details

  • Hide irrelevant details

  • Do not hide relevant details

Example: Bad: Pollution by repeating irrelevant technical details

Example: Good: No repeating technical details

Method Smells

  • Passing this to a method - it could be implemented with more, smaller and readable classes.

If you can mix a method's lines and it still compiles, it probably does more things. (Zoltan Peto :-)

Last updated

Was this helpful?