Search code examples
oopoptimizationreadabilityprinciples

Programming Principles: Assignement vs Conditions


I did some research but couldn't find the answer I was looking for so I figured I'd address this issue here. I guess it's better to demonstrate it using examples, so consider the following snippets of code:

int delta = 0;
if (some_condition)
    delta = 42;

x1 = regular_value1 + delta;
x2 = regular_value2 + delta;
// ...
// where delta is used a lot of times
// basically - if (some_condition == true) => add delta to all variables
// if FALSE - add 0 (thus, effectively not changing anything)

versus

int delta = 42;

if (some_condition)
{
    x1 = regular_value1 + delta;
    x2 = regular_value2 + delta;
    // ...
}
else
{
    x1 = regular_value1;
    x2 = regular_value2;
    // ...
}

For example, a very simple real-world scenario would be: Let's say I'm creating a windows form that might contain an image on the left and might not. If there's no image - create all the rest of form controls on the left, and if there's an image, shift all other controls to the right of the image (add delta to every control's X location).

I'm programming a C# XNA game (therefore performance is somewhat relevant, but OOP principles shouldn't be omitted by any means), thus my question is - which code would run faster provided that "some_condition" would be TRUE 50% of time? As well as, which code block is easier to maintain/read?

I'm aware that this isn't a huge issue, but I'm just trying to get into a habit of writing "the best" code possible. Any input and even personal experiences would be appreciated.

Thanks.


Solution

  • The latter might be slightly faster, or they may both be optimized to the same thing. That doesn't matter, you can always change it later if you find that it becomes an issue (which this particular case certainly won't - this is just general advice). But the former, I find at least, is easier to read and maintain. If you wanted to change regular_value1 or regular_value2, you only have to change it in one place, not two. Go for that.