Thursday, 29 September 2011

Weird if statement

I found the following if statement a long long time ago.

// determine if c lies between a and b
if (c == a || c == b || (c > a && c < b))
{
    doStuff();
}

Refactor.

Wednesday, 28 September 2011

Weird use of Conditional Operator

Found this gem in my companies code today.

It is not exactly that it is wrong, strictly speaking, it's just... well, you can probably guess yourself what I would rather see here.

public boolean checkIfWeHaveState() 
{
    return state != null ? stateDao.countStates(state) > 0 : false;
}

P.S. off the top of my head, the only reason why I would ever do something like the above, is if Java doesn't do Short-circuit evaluation (for example with the & operator).

Of course, the following example is often used, and here a conditional statement is warrented.

public int getRowCount() 
{
    return list != null ? list.size() : 0;
}

Of course, these are but very small issues in the grand scale of things, but it was Sherlock Holmes who said “To a great mind, nothing is little.”

Wednesday, 14 September 2011

Addendum on Post "Decrease Indentation"

This is a small addendum to my post on Decrease Identation

I noticed that the same thing can be done in for-loops and the like, by means of continue. I just don't know if it's in common use at the moment.

Bad example:
/**
 * Process the proper states.
 */

public void processStates()
{
    List<State> stateList = new ArrayList<State>();
   
    for (State state : stateList) 
    {
        if (!state.equals(State.INVALID))
        {
            Capital capital = State.getCapital();
            if (capital != null && capital.size() > 1000000)
            {
                stateList.add(state);
            }
        }
    }
    stateService.processStates(stateList);
    refresh();
}

Good example (bad example refactored):
/**
 * Process the proper states.
 */

public void processStates()
{
    List<State> stateList = new ArrayList<State>();
   
    for (State state : stateList) 
    {
        if (state.equals(State.INVALID))
        {
            // invalid state!!!
            continue;
        }
        Capital capital = State.getCapital();
        if (capital == null || capital.size() <= 1000000)
        {
            // capital doesn't exists or not impressive enough!
            continue;
        }
        stateList.add(state);
    }
    stateService.processStates(stateList);
    refresh();
}