'How can I return an empty response from a class?
public DataRule getRule(){
* code logic *
return null;
}
Instead of return null, how can I return an empty response? Is there any way to do that?
Solution 1:[1]
There are several options to return "no rule" from your method getRule().
The first and most simple way is, as you did already, to return null, but you want to avoid that.
Next is to try java.util.Optional, as Nikolai Shevchenko suggested in his comment:
public Optional<DataRule> getRule()
{
Optional<DataRule> retValue = Optional.empty();
/*
* Add some code here that determines a DataRule instance.
*/
retValue = new Optional.of( new DataRule() ); // for example …
return retValue;
}
Depending on the internal structure of DataRule, you can have an "empty rule", analog to an empty String: final String EMPTY_STRING = "";. This may look like this:
public static final DataRule EMPTY_RULE = … // Create an empty instance of DataRule
…
public DataRule getRule()
{
var retValue = EMPTY_RULE;
/*
* Add some code here that determines a DataRule instance.
*/
retValue = new DataRule(); // for example …
return retValue;
}
var dataRule = getRule();
if( dataRule == EMPTY_RULE )
{
…
}
else
{
…
}
The comparison with == works if you will always use the same EMPTY_RULE instance, otherwise you need to use if( rule.equals( EMPTY_RULE ) ) ….
Solution 2:[2]
You have to pick one: either return a null and check for that, or return Optional<DataRule> and check isEmpty(). The current best practice is to return Optional<DataRule> as that means that consumers of the method result have to consciously handle the possibility that no value is returned, whereas a null check is a kind of implicit "no value" value. The problem is that sometimes "null" means "no value", and sometimes it means something else, so it's ambiguous.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Tim Gustafson |
