Reputation: 4644
//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
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
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:
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