Sun, 07 Nov 2010 14:09:01 -0800, Walter Bright wrote: > Simen kjaeraas wrote: >> You misunderstand. The idea is this: >> >> void foo( ) { >> Object p; >> if ( m ) { >> p = new Object( ); >> p.DoSomethingThatNeedsToBeDoneNow( ); >> } >> // 20 lines of code here >> if ( m ) { >> p.doSomethingWeird( dataFromAbove ); >> } >> } > > You're right, the real cases where this kind of thing occurs are much > more complex. I just posted the thing boiled down. > > And, of course, there's always a way to refactor the code to eliminate > the spurious error message. But sometimes the result is as ugly as > Pascal's efforts to prove you really don't need a 'break' statement in a > loop. > > The real problem with the spurious errors is that then people will put > in an initialization "just to shut the compiler up." Time passes, and > the next guy is looking at the code and wonders why x is being > initialized to a value that is apparently never used, or worse, is > initialized to some bogus value randomly picked by the long-retired > programmer. I've seen code reviewers losing a lot of time on this issue.
That's why we have immutable variables. They force you to think what to put in the variables. A lot of cases like the one above would be solved if if-then-else was an functional expression instead of a void returning statement. C/C++/D has the ternary ?: but the syntax is obfuscated. Object p = if (m) { ... foo; } else { ... bar; } instead of Object p; if (m) { ... p = foo; } else { ... p = bar; } There are even cases where the former can be const. The latter one has to be mutable in any case.