asela38
asela38

Reputation: 4644

Which is the better of these two code fragments

//first
if(num % 2 == 0 ) {
  isEven = true;
}


//second
isEven = (num %2 == 0);

What is the best thing to do, and is first case a case of code smell?

Upvotes: 1

Views: 105

Answers (2)

Frank
Frank

Reputation: 10571

Without knowing anything about the surrounding context, these two version actually differ in their semantics.

The first version will only change the value of isEven if num is an even number. The latter version will always update the value of isEven. So I would definitely prefer the latter, as it ensures isEven holds a useful semantic value.

Upvotes: 2

Jon Skeet
Jon Skeet

Reputation: 1499860

They don't do the same thing - if num is odd, the first leaves isEven with its previous value, the second sets it to false.

I would:

  • Try to initialize the variable at the point of declaration, and not change it afterwards.
  • Use the second form in preference to the first in general.

When the body of an if block is just setting a variable, and the value can be expressed as some simple modification of the condition of the if block, and you always want to set some value, I would just use the simple assignment.

The same goes for return statements - I would rather have:

return (num % 2 == 0); // Or (num & 1 == 0)

than

if (num % 2 == 0) {
    return true;
} else {
    return false;
}

Upvotes: 7

Related Questions