Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is the right balance of predicates in a single if statement?

I personally have no problem with the following code

if (Object foo != null && !String.IsNullOrEmpty(foo["bar"]))
{
    // do something
}

Because I think the following is too verbose

if (Object foo != null)
{
    if (!String.IsNullOrEmpty(foo["bar"]))
    {
        // do something
    }
}

But I wouldn't go so far with this standpoint if say there were 5 predicates and I had to wrap the text in the editor to see them all at once, is there a logical "line" that you draw as to how many predicates you include in a single if statement in a similar sense to saying that methods should never require more than 7 parameters

like image 874
Nick Allen Avatar asked Apr 14 '09 10:04

Nick Allen


3 Answers

I don't think rewriting if-statements in two is the way, especially if you consider that adding an else clause to your examples gives different results. If I wanted to reduce the number of atomic propositions in the condition, I would factor some that make sense together to a function of their own, like:

if(won_jackpot(obj)) ...
like image 170
jpalecek Avatar answered Nov 16 '22 02:11

jpalecek


I think it's a balance of the different types of operators and correct formatting. If all of the operators are the same (all "and" or all "or"), then you can probably concatenate together an indefinite number of expressions without losing comprehension:

if (something() &&
    something_else() &&
    so_on() &&
    so_forth() &&
    some_more_stuff() &&
    yada() &&
    yada() &&
    yada() &&
    newman() &&
    soup_nazi() &&
    etc())
  ...
like image 43
1800 INFORMATION Avatar answered Nov 16 '22 02:11

1800 INFORMATION


Short term memory has a capacity of seven items, give or take two. This implies that an expression involving more than five dissimilar objects might require one to pause and think about it.

like image 36
Don Reba Avatar answered Nov 16 '22 02:11

Don Reba