I've got the following Java (8) code, think of it as a kind of calculator that reads numbers from a file and then applies an operation (with another number, both supplied by the user) to each one:
String originalstring = "-1000"; //read from the file
char symbol = '+'; //depends on user input
long numberone = 1000; //-"-
long numbertwo = 2000; //-"-
String newstring = "";
if(originalstring.charAt(0)=='-') {
switch(symbol) {
case '=':
newstring = numberone + "";
break;
case '+':
newstring = (Long.parseLong(originalstring) + numberone) + "";
break;
case '-':
newstring = (Long.parseLong(originalstring) - numberone) + "";
break;
}
} else {
switch(symbol) {
case '=':
newstring = numbertwo + "";
break;
case '+':
newstring = (Long.parseLong(originalstring) + numbertwo) + "";
break;
case '-':
newstring = (Long.parseLong(originalstring) - numbertwo) + "";
break;
}
}
An alternative would be to use switch on the outside and use the if statement in every case (possibly with the ternary operator to shorten it a little bit). Both versions would be approximately the same length and to me it also doesn't look like one version would be faster than the other, so:
What's the best practice for what should be inside and what should be outside if there aren't any loops (like in this question)? Is there even a best practice or does it simply come down to personal preference in cases like this where performance seems to be the same?
I'm aware that there's a third version: Keep the if/else, move the switch to its own function and either pass numberone or numbertwo as parameter but there's more code after this that works with newstring, so it would be harder to see how it's created and it would also be overkill for just 11 lines of code that aren't used again anywhere else.