I'm trying to do some conditional work like so:
Type object;
if (cond) {
doSomeStuff();
object = getObject();
doMoreStuff();
} else {
doSomeOtherStuff();
object = getDifferentObject();
doEvenMoreStuff();
}
use(object);
The only way I can think of solving this is the duplicate the use code (which is actually inline code in my application) and declare object in each branch of the if block. If I wanted to avoid duplicate code I'd have to wrap it in some use function, as I have above. In a real situation, this use function will probably take 5+ parameters to essentially carry over the context. This all seems messy, and impossible to maintain.
if (cond) {
doSomeStuff();
Type object = getObject();
doMoreStuff();
use(object);
} else {
doSomeOtherStuff();
Type object = getDifferentObject();
doEvenMoreStuff();
use(object);
}
What's the best approach to tackling this? Type has no default constructor, thus snippet 1 doesn't compile.
Some other languages support snippet 1 - Related question: Forcing uninitialised declaration of member with a default constructor