friendly-coins Rule #2: Don’t use the else keyword.

For some reason I expected that I would have a bunch of else’s. I didn’t. There were a grand total of four. Not much to say on this then. For the most part, it’s what you’d expect (but I’m saving the best for last, hang in there!):

BEFORE:


public int getCardinality( int denomination ) {
    if( containsDenomination( denomination ) ) {
        return denominations.get( denomination );
    } else {
        return 0;
    }
}

AFTER:


public int getCardinality( int denomination ) {
    if( containsDenomination( denomination ) ) {
        return denominations.get( denomination );
    }
    return 0;
}

This of course violates the prescription “Only have one exit point for a method” – and also increases the cyclomatic complexity. But, these are both Allowed for this exercise. Besides, I must say I’d choose the AFTER aver the BEFORE any day.

It’s not always that simple:

BEFORE:


private void accumulateTotal(CoinSet coinSet) {
    if( 0 == total ) {
        total = coinSet.sum();
    } else if( coinSet.sum() != total ) {
        throw new IllegalStateException( "All coinSets must have the same sum" );
    }
}

AFTER:


private void accumulateTotal(CoinSet coinSet) {
    if( 0 == total ) {
        total = coinSet.sum();
        return;
    }
    if( coinSet.sum() != total ) {
        throw new IllegalStateException( "All coinSets must have the same sum" );
    }
}

I like the BEFORE in this case. Assuming that is that I like the throwing of the exception – which, no, I don’t. Never mind, this all gets refactored later on anyhow.

Much more gratifying than either of the above is the chance to get rid of plain bad smelling code, by reducing the number of variables, curlies, and dropping the else:

BEFORE:


public static String stringJoin( Collection objects, String joiner ) {
    StringBuilder builder = new StringBuilder();
    boolean first = true;
    for( Object o : objects ) {
        first = stringJoinAppend( o, joiner, builder, first );
    }
    return builder.toString();
}	

private static boolean stringJoinAppend( Object o, String joiner,
        StringBuilder builder, boolean first ) {
    if( ! first ) {
        builder.append( joiner );
    } else {
        first = false;
    }
    builder.append( (null == o) ? "null" : o.toString() );
    return first;
}

AFTER:


public static String stringJoin( Collection objects, String joiner ) {
    StringBuilder builder = new StringBuilder();
    String useJoiner = "";
    for( Object o : objects ) {
        stringJoinAppend( o, useJoiner, builder );
        useJoiner = joiner;
    }
    return builder.toString();
}

private static void stringJoinAppend( Object o, String joiner,
        StringBuilder builder ) {
    builder.append( joiner );
    builder.append( (null == o) ? "null" : o.toString() );
}

Leave a Comment