Search code examples
c++c++11c++17coding-style

C++ how can I simplify this if else statement?


I would like to know how I could simplify a statement like the one below.

I have similar code everywhere, and would like to clear it up.

if(isActive)
{
    if(columnId == 4)
        g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true);
}
else
{
    if(columnId == 4)
        g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true);
}

isActive, as you can imagine, is a bool value.


Solution

  • At first glance, it's most apparent that this code only does anything if columnId == 4.

    if(columnId == 4)
    {
        if(isActive)
        {
            g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true);
        }
        else
        {
            g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true);
        }
    }
    

    At second glance, those two bulky lines are almost the same.

    if(columnId == 4)
    {
        auto & text = isActive ? active : inactive;
        g.drawText(text[row].value, 2, 0, width, height, Justification::centredLeft, true);
    }
    

    Note, also, the valid comment from @eerorika. ⬇️ I couldn't say it better than they did.