tags:

views:

283

answers:

13

Which one of the following do you do:

var = true;
if (...) var = false;

Or

if (...) var = false;
else var = true;

Is there a reason you pick on or the other?

I'm working on the premise that nothing else is happening to var. The next line of code might be something like:

if (var) { ... }
+1  A: 

Depends on the context. I would use the second option when it is clear that 'var' needs to be true when IF fails.

Daniel
+3  A: 

You could also use a ternary operator if your language supports it :)

I would generally only do the first one if there was a chance the IF could fail and the variable must have a default value if it does.

Steven Robbins
+9  A: 

how about var = { ...} directly since it's boolean ?

krosenvold
This is nice, but works only if there is only one single assignment statement in the if-block and the variable is a boolean as in this simple example.
0xA3
+1  A: 

I use the first type unless the value to set requires significant computation.

Mehrdad Afshari
A: 
ForYourOwnGood
"var x;" won't work, because the type cannot be inferred.
Rauhotz
I'm pretty sure the poster of this answer was intending this to be pseudo-code, not C# code.
Jason Baker
your scope's most likely wrong, though - at least in C++ the variable would be scoped to the code block
warren
this is sudo-code, I didn't relize so many people would be offended by the syntax.
ForYourOwnGood
+5  A: 

I prefer the second in Java, doing something like this:

int x;
if (cond) {
  x = 1;
} else {
  x = 5;
}

because if something is changed later (for example, I turn the else block into an else if), the compiler will tell me that the variable has failed to be initialized, which I might miss if I used your first strategy.

Ross
And possibly add final.
Tom Hawtin - tackline
A: 

Depends on the language. In C++, I would highly recommend setting it to a default as quickly as possible otherwise you risk getting garbage results.

In most other languages, you can be a bit more flexible. In fact, I would argue that it's more readable to explicitly define the conditions than to set a default.

Jason Baker
+2  A: 

If you set the default, then you reset it again later to something else, although it's a very small amount, its still a waste of resources. So, most of the time, for most of the code, a balanced if/else or even a (?:) syntax, are clearer and more appropriate, except:

Sometimes, if what you doing is building fall-through code (or a decision function), where you start with a specific condition, and then test a whole bunch of other conditions to see if that changes, then you want to definitely set the default first:

int final = 27;

if ( some condition ) final = 86;

if ( another condition ) {
    final = 98;
    return final;
}

if ( some state ) {
   final += 2;
}

return final;

Or something similar to that.

BTW: in your example, if you set 'var', then the next line just tests 'var', you don't really need 'var' do you? If the condition is so ugly that using 'var' helps make it readable, then your probably best to move the condition into it's own function, accepting that the extra function call is there to help readability. In general, you can waste resources, if and only if you get something significant, such as readability, in return.

Paul.

Paul W Homer
A: 

Since the variable is not written to later, for general values I would write the following in Java:

final Type var;
if (cond)
{
    var = value1;
}
else
{
     var = value2;
}

The Java compiler will catch the error that var is not assigned a value before it is used. The final keyword expresses the fact that the variable is constant after the conditional.

In your exact case with booleans I would use

final boolean var = !cond;

Using a conditional in this case indicates you are afflicted by "booleanophobia".


In C I would initialize the variable at its declaration.

starblue
+1  A: 

Always the first as many people have said. However it's worth emphasising why, and that's because it makes the program more resistant to future bugs caused by incorrect maintenance.

For example, it's quite common for some additional business condition to arise and a maintenance coder add some extra condition or two inside the if to include more business logic and incorrectly amend the code - for example

if (a==b) {
  if (a==c) {
    [new logic]
    var=false
  }
}
else {
  var = false
}

On the face of it it looks unlikely, but it happens alarmingly often (in fairness often the situation arises after the original if has got a lot more complex). Putting the initialisation first prevents this.

Cruachan
A: 

I generally set the "default" value and use if statements to modify it. If no default exists then only the if statements.

int timeout = 100;
if (moreTime) timeout = 1000;

int searchOption = null;
if (sometest1) searchOption = 1;
if (sometest2) searchOption = 2;

// then later..
if (searchOption != null)
  .....
Chris Nava
A: 

If the initialization is complex enough that a direct expression can't be cleanly written, I sometimes find it useful to handle this case as

boolean isFoo = determineWhetherFoo(...);

where determineWhetherFoo takes whatever arguments are necessary to make the determination and returns the appropriate boolean result. This makes it very clear what the variable means and what it depends on. Initializing a variable to a possibly-wrong value, followed by a wad of code that may change its value, can sometimes obscure what's being expressed.

joel.neely
A: 

Wherever you write an if() also write the else - even if it's empty.
The complier will optimise it away but it forces you (and any programmers after you) to think about when the if () isn't triggered, what are the consequences?

Martin Beckett