I'm reading some Java textbooks trying to learn a new language and I came across this method.
private String monthName (int month) { // bad example since this method needs to return a String
switch (month) {
case 1:
return "January";
case 2:
return "February";
...
case 12:
return "December";
}
}
The statement following this code says:
The compiler will reject this code because it is possible to reach the end with- out returning a value.
So in Java, I assume that if a method has the word "String" before the method name, it MUST return a String? The problem with this switch statement is that perhaps no case statement condition is satisfied and execution just drops out of the bottom? Is it necessary for methods that are not labeled to void to ALWAYS return a value?
A method signature is a contract that specifies what it takes as arguments and what it is obligated to return. A method declared to return something other than void must either return something or throw something, it's not allowed to fall off the end without returning anything (if it did, the variable getting assigned the return value from the method call would still have to be assigned something).
Specifically, if a method is declared to return a String, either every possible path taken through that method must end with returning a String, returning null (null is an allowed value of any reference type), or throwing an instance of Throwable. That's what the quoted passage is telling you, the compiler can detect that you haven't done this and will complain about it.
Here you could have your code throw an exception if the integer passed in is not in the expected range. It's a good thing to have your methods validate that they are receiving reasonable values for their arguments. Using a default value or returning null is not as good because instead of exposing the problem immediately it sticks the caller with a value that may not make sense for it, and makes it harder to debug what happened because the place where the error is visible may be a long way from where the cause of the problem originated. This method could be written as:
private String monthName (int month) { // bad example since this method needs to return a String
switch (month) {
case 1:
return "January";
case 2:
return "February";
...
case 12:
return "December";
default:
throw new IllegalArgumentException("found unexpected value " + month);
}
}
so that the compiler won't complain, and any out-of-range values will come to your attention.
Be aware:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With