Better if the / else statement

This works for any language, but I noted C # because this is what I am using at the time.

I have several statements that I want to run when one of the two conditions is true, but then some additional special instructions, depending on which was true (only one could be true)

if( condition1 || condition2 )
{
    statement1;
    statement2;

    if( condition1 )
        additional_statement1;
    else // (condition2)
        additional_statement2;
}

      

It just seems sloppy (I'm testing the "condition1" condition twice) and only used the OR operator because I needed the same answer from both conditions, but now the improvement requires a slightly different answer. Is there anyway to do this?

+3


source to share


1 answer


This approach isn't that bad. Operators are if

pretty cheap and fast if the conditionals themselves are cheap and fast. That being said, you can wrap common functionality in a function:

if (condition1)
{
   CommonFunction();
   //CustomStuff
}
else if (condition2)
{
    CommonFunction();
    //Other stuff
}

      



This avoids the copy paste problem and minimal execution of conditionals.

+5


source







All Articles