Wednesday, May 14, 2014

Simplied reading of code

So I recently was working on refactoring a piece of code I found online. It was this:
if (this.itemUnderDragCursor == newItem)
    return;

// The first pass handles the previous item under the cursor.
// The second pass handles the new one.
for( int i = 0; i < 2; ++i )
{
    if( i == 1 )
        this.itemUnderDragCursor = newItem;

    if( this.itemUnderDragCursor != null )
    {
        UIElement item = this.GetSelectorItem(this.itemUnderDragCursor);
        if( item != null )
            SelectorItemDragState.SetIsUnderDragCursor( item, i == 1 );
    }
}
Now looking at this code, it's tough to tell what exactly it does. Refactoring it, same functionality, but much easier to read:
void UpdateItemUnderDragCursor(object newItem)
{
    if (this.itemUnderDragCursor != newItem)
    {
        SetItemSelectedState(itemUnderDragCursor, false);
        itemUnderDragCursor = newItem;
        SetItemSelectedState(itemUnderDragCursor, true);
    }
}

private void SetItemSelectedState(object itemToSetState, bool state)
{
    if (itemToSetState != null)
    {
        UIElement item = this.GetSelectorItem(itemToSetState);
        if (item != null)
            SelectorItemDragState.SetIsUnderDragCursor(item, state);
    }
}
Lesson here is that code can be made complex to read and maintain or can be made easy.