I want to avoid this ugly pattern:
Long foo = null;
Double bar = null;
try {
foo = Long.parseLong(args[0]);
bar = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.exit(1);
}
doSomethingWith(foo, bar);
I know I can move the initialisations and doSomethingWith
into the try
block, but imagine:
doSomethingWith
is actually several lines of conditional logic, many method calls, statements etc.- I don't want to be nesting blocks unnecessarily deeply
- I want to avoid accidentally catch unexpected
NumberFormatException
s thrown fromdoSomethingWith
.
I find the = null
and above quite ugly, as well as the use of classes instead of primitives. This ugliness makes me suspect there's a better way to write this code.
My first vision is of course
long foo;
double bar;
try {
foo = Long.parseLong(args[0]);
bar = Long.parseLong(args[0]);
} catch (NumberFormatException e) {
System.out.println(USAGE);
System.exit(1);
}
doSomethingWith(foo, bar);
but we all know Java throws a couple variable might not have been initialized
errors when you try to build that.
What's a better design pattern for this kind of problem? "Better" meaning (for me) does all of this
- avoids the weird
= null
- avoids unnecessary class wrappers around primitives
- doesn't nest deeply into the
try
block - doesn't catch/hide exceptions it wasn't meant to
If this is not possible, or if my concept of "pretty" code is wrong, please convince me and show the best that can currently be used.