8th Light: Day 95 + 2

15 May 2016 . 8thlight . Comments #apprenticeship #8thlight #software #code-smells

Code smells: Temporary field

Temporary fields get their values (and thus are needed by objects) only under certain circumstances. Outside of these circumstances, they are empty - sourcemaking.com

Temporary fields are variables that live inside a method, and are use within that method. For example:

public int foo(int a, int b) {
    int bar = a * b;
    if(bar > 100) {
        return bar * 0.95;
    } else {
        return bar * 0.25;
    }
}

Would be better if the temporary variable bar was inlined (Inline temp)

public int foo(int a, int b) {
    if(a * b > 100) {
        return a * b * 0.95;
    } else {
        return a * b * 0.25;
    }
}

Even better would be using the Extract method and move the expression the a new method that can be tested.

public int foo(int a, int b){
    if(bar(a,b) > 100) {
        return bar(a,b) * 0.95;
    } else {
        return bar(a,b) * 0.25;
    }
}

public int bar(int a, int b) {
    return a * b;
}

The end result with either method above is easier to read code and easier testing.