Should a retrieval method return 'null' or throw an exception when it can't produce the return value?
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do other places in the code? Consistency is important.
Should a retrieval method return 'null' or throw an exception when it can't produce the return value?
If you are always expecting to find a value then throw the exception if it is missing. The exception would mean that there was a problem.
If the value can be missing or present and both are valid for the application logic then return a null.
More important: What do you do other places in the code? Consistency is important.
Throw an exception or return null
About your options, ask yourself if
- Is it a good idea to have your program blow up at some point after this method returned an unexpected value (i.e.
null
)? - What exactly will be hidden if you mask out the
null
return value? - Is it a good idea to blow up immediately, just because there was a wrong value?
Personally I'd go for option 2 or 3, depending on whether I like the answer to question 2 or 3 better. Option 1 definitely is a bad idea, especially if it's not supposed to happen. If the program throws a NPE way after your function returned, you'll have a hard time figuring out where the null
came from. Especially if it happens months after you finished working on this particular function.
If you choose to throw an exception, you immediately see where something went wrong and you can directly go there to figure out why it went wrong. Returning null
and checking for it in the calling function could also work, but only if you don't fail silently, but actually do something to handle the problem properly.
Is it more Java-thonic to throw an exception or return null?
This is an esoteric question!
The conventional wisdom is this:-
Don't use exceptions for control flow. Exceptions should be left for when something exceptional happens
This implies returning a NULL and checking for it. i.e. choice (1)
But here is an interesting discussion on this very subject in the context of the Java language.
In a nutshell, as Java's exception system is so flexible, sometimes throwing exceptions and using them to control program flow, can be a sensible way of making the logic of a program more readable and maintainable.
What is the purpose of NoSuchMethodException instead of returning null
It appears that the designers of Java APIs made a distinction between situations when it's OK to ask for something that is missing and situations when you are supposed to ask only for things that exist.
They decided that asking for a missing key in a Map
is OK, because the content of a map is something your program controls at runtime. Therefore, designers of the class library decided that it is unreasonable to ask programmers to check if a value is present before calling Map.get
, and decided to return null
instead.
The list of methods in a class, however, remains static at all times during a particular run, so it becomes reasonable to ask programmers to call getMethod
only for methods that do exist. There are two consequences to this approach:
- You can request multiple methods without checking each one - if you have a list of methods that must exist, for example, in a plugin component, you can get their
Method
reflection objects without checking the return value of individualgetMethod
calls, and - When you do not know if a method exists, call
getMethods()
- You can still examine all methods without knowing their names by getting a full list from theClass
object.
Here is a code example to illustrate the first point. Current API lets you write this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
try {
init = cl.getMethod("init");
start = cl.getMethod("start");
stop = cl.getMethod("stop");
} catch (NoSuchMethodException ex) {
throw new PluginException("Plugin is missing a required method", ex);
}
}
...
}
instead of this:
class Plugin {
private final Method init;
private final Method start;
private final Method stop;
public Plugin(Class cl) throws PluginException, SecurityException {
init = cl.getMethod("init");
if (init == null) {
throw new PluginException("Plugin is missing init method");
}
start = cl.getMethod("start");
if (start == null) {
throw new PluginException("Plugin is missing start method");
}
stop = cl.getMethod("stop");
if (stop == null) {
throw new PluginException("Plugin is missing stop method");
}
}
...
}
When is it correct to return a null reference type in C#
Yes you can return null
likewise you are currently doing and in which case the responsibility lies to caller to check for nullity before trying to access any of the property of the object. Using C# 6 syntax
muobject?.Age
Per pattern you can use Null Object Pattern
; in which case you return an empty object instead of returning null
. Thus even if caller mistakes it won't blow up with a NullRefException
. For validation purpose you can check for the property value like if(string.IsNullOrEmpty(myobject.name)) ....
Is it right return null?
Is it right to return null,if object not found in array
This is a common choice, unless of course having null
in the array is valid. This is what Map#get
does, for instance. And the fact that it's what Map#get
does means that if you have a map where it's valid to store null
s, you have to call containsKey
first to know whether get
returning null
means not found or means that the key is mapped to null
. (Which is awkward.)
Here's a roundup of your options, which are not all mutually-exclusive:
Return
null
if not found.Throw if not found.
Offer a
findIndex
method that finds the index of the product, returning -1 if not found.Offer both a throwing version (
findByProductName
) and anull
-returning version (findByProductNameOrDefault
), and let the caller decide which is best for their scenario.Offer an optional argument that's the value to return if not found; the caller can then pass
null
if that's what they want, or something else.Offer a lambda callback for the "not found" case; again the caller can do what they want in the lambda.
Side note: The overwhelming convention in Java is that method names start with a lower-case letter, e.g. findByProductName
rather than FindByProductName
.
Related Topics
How to Share Data with Two(2) Swingworker Class in Java
Handling Parenthesis While Converting Infix Expressions to Postfix Expressions
The Case Against Checked Exceptions
What Are the Differences Between the Different Saving Methods in Hibernate
How to Execute Command with Parameters
What Is the Backslash Character (\\)
What Are All the Different Ways to Create an Object in Java
Custom Method for Update Query With Spring Data Mongorepository
Retrieve Column Names from Java.Sql.Resultset
Is There a Concurrent List in Java's Jdk
Split String into Array of Character Strings
Page Scroll Up or Down in Selenium Webdriver (Selenium 2) Using Java