I have read the whole thread. There is some food for thought, but in
general I like the 2nd method. Reasons:
1. Limiting the scope is usually not THAT important. If you have
multiple items with the same thing in the same routine, just in
different scopes, your code is going to be very confusing.
Having short enough functions would be ideal, but in reality we don't
enjoy that all the time. I've had to maintain legacy code which has
functions that are hundreds of lines long, where introducing name into
scope can be a big deal. Some even has "goto quit;", and defining an
object (with ctor/dtor) between the goto and the label will break the
goto, so you have to limit the scope manually:
if (...) goto quit;
// ...
{ // limit the scope of obj
X obj(...);
// ...
}
// ...
quit:
2. When debugging, you can breakpoint on the line with the call.
Depending on the debugger, you may not easily be able to step into
GetThing(). Stepping out also could get interesting.
Why is this a problem? No matter whether you have
if (Thing* pThing = getThing()) {
// ...
}
or
Thing* pThing = getThing();
if (pThing) {
// ...
}
you can always set a breakpoint on the line that has the call to
getThing(), and the debugger will stop before the call, and you have
the choice to step into or over the call. (This is based on my
experience with GDB, and other debuggers may vary, but it would be
surprising if any decent one didn't support this.)
3. As a matter of taste, I don't like doing multiple things on the
same line, let alone in the same statement. Things can get really
muddy.
I can agree on this. Especially when multiple side effects are involved
and especially more when I care about their order. Less when only a
single side effect is involved (e.g. assigning to an object and
inspecting it); otherwise I'd have to give up neat things like:
while (std::getline(in, str)) { ...}
4. I make exceptions for for loops. Declaring the iterator in the loop
statement is pretty clear. Doing one or more function calls within an
if statement just muddies things up. And the "=" vs "==" can shoot you
right in the foot. And my feet have enough holes in them, thank you
very much.
What about doing one or more function calls in the "condition" part or
the "iteration" part in for loops? (Just curious.)