Avoid Literals In If Condition - java

This part of code is rejected by pmd in sonar:
public String getFoo() {
String foo = System.getProperty("foo");
if (foo == null) {
foo = System.getenv("foo");
} else if (foo == null) {
foo = "defaultFoo";
}
return foo;
}
It says "Avoid Literals In If Condition". Can someone tell me what's wrong with this or what this rule try to effect?

Why don't you use:
public String getFoo() {
String foo = System.getProperty("foo", "defaultFoo");
return foo;
}
It will return "defaultFoo" if no property is found.
http://docs.oracle.com/javase/7/docs/api/java/lang/System.html#getProperty(java.lang.String, java.lang.String)

What does Sonar try to say is that you should avoid hardcoded literals (like null) in the if condition.
Suppose the following example:
Let's say we have this if statement, for which Sonar warns with Avoid Literals In If Condition:
if (i == 5) {
//do something
}
By declaring the hardcoded literal as (final) variable with descriptive names maintainability is enhanced:
final int FIVE = 5;
if (i == FIVE) {
//do something
}
and Sonar doesn't warn anymore.

Related

Java 8 Optional-class: return value if nullable

I'm trying to convert an existing snippet of code to some fancy Java 8 one-liner.
private static final Map<Integer, Foo> FOO_MAP = ...
public static Foo getForCode(final Integer code) {
if (code == null) {
return null;
}
final Foo foo = FOO_MAP.get(code);
if (foo== null) {
throw new IllegalStateException("Unknown foo for code: " + code);
}
return foo;
}
My solution so far, which is lacking the handling if the param is null.
public static Foo getForCode(final Integer code) {
return Optional.ofNullable(code).map(FOO_MAP::get)
.orElseThrow(() -> new IllegalStateException("Unknown foo for code: " + code));
}
you can returning Optional<Foo> from getForCode(final Integer code) and let the client deal with the optional value returned.
public static Optional<Foo> getForCode(final Integer code) {
return Optional.ofNullable(code).map(FOO_MAP::get);
}
Without changing the behavior of the original function, I don't think Optional buys you anything here, except the opportunity to bury some complex conditionals within its methods and lambdas. If you were to minimize the conditional expressions, using if-statements and boolean expressions, you'd end up with this:
Foo getForCode(Integer code) {
Foo foo = null;
if (code == null || (foo = FOO_MAP.get(code)) != null) {
return foo;
} else {
throw new IllegalStateException("Unknown foo for code: " + code);
}
}
This is a tad more readable than any solution using Optional, to my eye, though it's still pretty obscure.
If you're willing to change the semantics of the function, and to return an Optional, then the suggestion from Roshane Perera seems like a reasonable approach (+1).
It's not very readable, but you can :
Foo result = Optional.ofNullable(code)
.map(x -> Optional.ofNullable(FOO_MAP.get(x))
.orElseThrow(() -> new IllegalStateException("Unknown foo for code: " + code)))
.orElse(null);
You could handle it alone first.
Trying mixing both cases in a single statement may make it less readable.
Note that actually you usage of Optional is probably not required.
Optional makes more sense for return type. In your actual code you go on to return null value.
Here is a usage of Optional where you return an Optional to handle both cases a returned Foo and no returned Foo:
public static Optional<Foo> getForCode(final Integer code) {
if (code == null)
return Optional.empty();
Optional<Foo> optional = Optional.ofNullable(map.get(code));
if (!optional.isPresent()) {
throw new IllegalStateException("Unknown foo for code: " + code);
}
return optional;
}

Java - How to deal with null value passed by argument? [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
I wrote this simple function:
private String getOperatorForCardinality(String op)
{
String operator ="";
if(op!=null)
{
if(op.equals(">="))
{
operator = ">=";
}
else if (op.equals("<="))
{
operator = "<=";
}
}
else
{
operator = "empty";
}
return operator;
}
which returns a string.
In the main program I call this function, when the argument is null the compiler displays the error of NullPointerException.
The reason is pretty clear, but I do not know how to deal with the null value when is passed by argument.
It is impossible for the code you posted to throw a NPE. The error is somewhere else, or you are not running the code you think you are (ie haven't recompiled etc).
That said, your method can be simplified to:
private static List<String> OPS = Arrays.asList("<=", ">="); // can add more valid ops
private static String getOperatorForCardinality(String op) {
if (op == null)
return "empty";
return OPS.contains(op) ? op : "";
}
Or if you don't mind nested ternaries:
private static String getOperatorForCardinality(String op) {
return OPS.contains(op) ? op : op == null ? "empty" : "";
}
Less code is usually clearer code, and leaves less places for bugs to lurk.
It is called defensive programming and you should do something like:
private String getOperatorForCardinality(String op) {
if(null == op) {
//return null;
//throw new NullPointerException("...");
}
....
}
You should think about how your method should react, need to return null if parameter is null or throw an exception? Generally you cant be sure a parameter will never be null so you have always to check and take action.
This can't throw a null pointer exception:
private String getOperatorForCardinality(String op)
{
String operator = "";
if(">=".equals(op))
{
operator = ">=";
}
else if ("<=".equals(op))
{
operator = "<=";
} else {
operator = "empty";
}
return operator;
}
try opposite
if (op==null)
operator = "empty";

What is so terribly wrong with this code? It appears semantically correct to me

Saw in a blogpost that this kind of code drives the author insane.. Why?
public boolean foo() {
boolean b = bar();
if (b == true) {
return true;
}
else {
return false;
}
}
Because there is a much shorter version of it:
public boolean foo() {
return bar();
}
As others have noted, the whole function foo may be redundant. There are however situations where it cannot be eliminated, for example if it is defined in an interface you are implementing or if bar is private.
The construct if (b == true) is especially dangerous for inexperienced programmers, as it could be wrongly written as if (b = true). This problem is not caught by the compiler but would silently always execute the true branch of the if.
Because it could be written as
public boolean foo() {
return bar();
}
The code is unnecessarily complex.
Because the call to foo() (and the entire function itself) can be replaced with bar().
Anytime you write:
if (something == true) {
return true;
} else {
return false;
}
All you're doing is returning the value of something, so why not just return something;? And at that point in the code you provided in OP, the entire function has no point to exist since it's just returning the return value of another function.
Another similar use case (and equally annoying) is:
Foo foo = getFoo();
if (foo == null) {
return null;
} else {
return foo;
}
of all above answers, I think you don't even need to call foo().
just use
if(bar())
directly at the place where you are calling foo()
no need of foo() function at all

calling function should return default value, if object (or any function result) is null

Is it possible to wrap following code in a reusable function?
EDIT: this is just an example, I want a working solution for ALL recursion depths
what I want is that following code is generated:
if (MyObject o == null ||
o.getSubObject() == null ||
o..getSubObject().getSubSubObject() == null /*||
... */)
return defaultValue;
return o.getSubObject().getSubObject()/*...*/.getDesiredValue();
by calling something like
Object defaultValue = null;
Object result = NullSafeCall(o.getSubObject().getSubObject()/*...*/.getDesiredValue(), defaultValue);
The seond code block is just an idea, I don't care how it looks like, all I want is that I, if desired, can avoid all the null checks before calling a deeper function...
Injection could do this propably, but is there no other/easier solution? Never looked at injection before yet...
EDIT2: example in another language: http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator
Not really, any code you would write this way would look horrible and/or use very slow reflection. Unless you use an actual Java preprocessor that can understand and change the code you've written.
A better (but associated with quite a bit of refactoring) approach would be to make sure that the values in question cannot possibly be null. For example, you could modify the individual accessors (getSubObject(), getDesiredValue()) to never return null in the first place: make them return default values. The accessors on the default values return default values in turn.
Java8 helps to get the closest you'll get to your syntax with decent performance I suspect;
// Evaluate with default 5 if anything returns null.
int result = Optional.eval(5, o, x->x.getSubObject(), x->x.getDesiredValue());
This can be done with this utility class;
class Optional {
public static <T, Tdef, T1> Tdef eval(Tdef def, T input, Function<T,T1> fn1,
Function<T1, Tdef> fn2)
{
if(input == null) return def;
T1 res1 = fn1.apply(input);
if(res1 == null) return def;
return fn2.apply(res1);
}
}
Sadly, you'll need a separate eval() defined per number of method calls in the chain, so you may want to define a few, but compile time type safe and reusable with just about any calls/types.
You can do something like this
public static Object NullSafeCall(MyObject o,Object defaultValue){
if ( o == null || o.getSubObject() == null)
{
return defaultValue;
}
else
{
return o.getSubObject().getDesiredValue();
}
}
Now you can call this method as follows
Object result = NullSafeCall(o, defaultValue);
i would suggest just replace
Object result = NullSafeCall(o.getSubObject().getDesiredValue(), defaultValue);
by the
Object result = (o == null || o.subObject == null) ? defaultVlue : o.getSubObject().getDesiredValue();
Create method only if you can reuse it......
What you want is not possible. It is essential to understand that using this syntax: Object result = NullSafeCall(o.getSubObject().getSubObject() ...); the part of o.getSubObject().getSubObject() will be evaluated before any control passes to the function/method thus throwing the exception.
It is required to have some type of context before executing such code. The closest to this I could think of, can be done using anonymous inner classes like the example below:
// intended to be implemented by an anonymous inner class
interface NullSafeOperation<T> {
public T executeSafely();
};
// our executor that executes operations safely
public static class NullSafeExecutor<T> {
public NullSafeExecutor() {}
public T execute(T defaultValue, NullSafeOperation<T> nso) {
T result = defaultValue;
try {
result = nso.executeSafely();
} catch(NullPointerException e) {
// ignore
}
return result;
}
// utility method to create a new instance and execute in one step
public static <T> T executeOperation(T defaultValue, NullSafeOperation<T> nso) {
NullSafeExecutor<T> e = new NullSafeExecutor<T>();
T result = e.execute(defaultValue, nso);
return result;
}
}
public static void main(String[] args) {
final String aNullString = null;
String result = NullSafeExecutor.executeOperation("MyDefault", new NullSafeOperation<String>() {
#Override
public String executeSafely() {
// trying to call a method on a null string
// it will throw NullPointerException but it will be catched by the executor
return aNullString.trim();
}
});
System.out.println("Output = " + result); // prints: Output = MyDefault
}

code style: multiple returns

I'm writing a method along these lines:
if (hasFoo()) {
return calculateFoo();
} else if (hasBar()) {
return calculateBar();
} else {
return calculateBaz();
}
The getters are rather expensive and the has...() checks would either duplicate a lot of the logic or just have to reuse the getters. I could have the has...() methods store the result of the get...() in a field and make the getter lazy, but it would be nice for has...() not to have any side effects. I could write this with nested try{} catch{} blocks, but that doesn't look elegant. seems like there should be a better solution to this...
EDIT: changed get...() to calculate...() to make it clear that they're expensive.
int result = 0;
if (hasFoo()) {
result = getFoo();
} else if (hasBar()) {
result = getBar();
} else {
result = getBaz();
}
return result;
is the idiom I prefer to use - makes it far easier to inspect variable values while debugging.
I see nothing wrong in doing
Object fooBarBaz = null;
if (hasFoo()) {
foo = getFoo();
} else if (hasBar()) {
fooBarBaz = getBar();
} else {
fooBarBaz = getBaz();
}
return fooBarBaz;
I prefer it this way:
if (hasFoo()) {
return calculateFoo();
}
if (hasBar()) {
return calculateBar();
}
return calculateBaz();
All a matter of taste and convention.
I am not sure if this is your case, but I would try to fully refactor the code. Currently, as far as I understand, your code looks something like this (example):
boolean hasFoo() {
DataObject do = getSomeDataSource().getSomeDataObject();
if (do.getF() != null && do.getO() != null) {
return true;
} else {
return false;
}
}
Foo getFoo() {
DataObject do = getSomeDataSource().getSomeDataObject();
Foo result = new Foo(do.getF(), do.getO());
return result;
}
Basically what happens here is that the same code is used to check if Foo can be returned and to construct the Foo itself too. And I would refactor it to this:
/**
* #returns instance of Foo or null if Foo is not found
*/
Foo getFoo() {
DataObject do = getSomeDataSource().getSomeDataObject();
F f = do.getF();
if (f == null) {
return null; //Foo can not be created
}
O o = do.getO();
if (o == null) {
return null; //Foo can not be created
}
return new Foo(f,o);
}
Now your original code would become similar to this:
Result r;
r = getFoo();
if (r == null) {
r = getBoo();
}
if (r == null) {
r = getDoo();
}
return r;
This is not an "is it OK to do multiple returns" problem - your multiple returns are fine.
This is a refactoring and/or state storage problem.
If you have:
bool hasXXX() {
// do lots of stuff
...
return has_xxx;
}
and
double calculateXXX() {
// do the same lots of stuff
...
// do some more stuff
...
return xxx;
}
then the complexity of the problem depends on whether the hasXXX() calculation produces lots of intermediate values that are necessary for calculateXXX().
You likely need something like:
bool checked_xxx = false;
double xxx_state;
bool hasXXX() {
// do expensive stuff
...
// save temporary state variables
xxx_state = ...
// remember that we've been here
checked_xxx = true;
// send back the required value
return has_xxx;
}
double calculateXXX() {
// make sure that hasXXX was called, and is valid
if (!checked_xxx && !hasXXX()) {
// should never happen - you called calculateXXX when hasXXX() == false
throw new RuntimeException("precondition failed");
}
// use the previously calculated temporary state variables
...
// send back the final result
return xxx;
}
EDIT: If I'm interpreting your comments correctly, it sounds like you actually want something like:
Result result = calculateFoo();
if (result != null) {
return result;
}
result = calculateBar();
if (result != null) {
return result;
}
return calculateBaz();
... where each of the calculate methods returns null if the corresponding has method returns false. Now if null is a valid "real" return value, you could always wrap the result so that calculateFoo returns a value which can basically say, "Yes, I've got a valid value and it's X" or "no, I haven't got a valid value" (a "maybe" type).
Original answer
I would keep your code exactly as it is. I see no problems with having multiple return statements when that's the clearest approach - and in this case I believe it is.
You're making it clear that once you've reached each of the "leaf" parts, you know exactly what the return value is, and the only other code which should be executed before leaving the method is any clean-up code in finally blocks.
Having a single exit point makes sense in languages which don't have try/finally or GC (where you really want to make sure you do all the cleanup in a single place) but in Java, I think returning when you know the result states your intention more clearly than using a separate local variable.
Having said that, another alternative to consider is using the conditional operator, laying out your code so it's obviously going through a series of tests and returning as soon as it finds the first "match":
return hasFoo() ? getFoo()
: hasBar() ? getBar()
: getBaz();
The disadvantage is that this pattern looks a little odd the first time you see it - but once you get used to it, I find it a really neat way of encoding this sort of logic.
Instead of doing hasXXX() and calculateXXX() you could factor those calculations out to separate objects eg
public interface CalculationModel {
Object calculate();
}
public class FooCalculationModel implements CalculationModel {
#Override
public Object calculate() {
// Perform Foo calculations
return result;
}
}
and your if-statement can then be replaced with:
return getCalculationModel().calculate();
You will need some way of deciding the CalculationModel of course, but this would then replace the hasFoo(), hasBar() etc methods.
you could do something like this :
Object bar;
if ((bar = getFoo()) != null) {
return bar;
} else if ((bar = getBoo()) != null) {
return bar;
} else {
return getBaz()
}
this way you only need to call the get methods, but not the has ones
EDIT
this is the same in a more readable format that also elminates the need to call the has methods
Object bar = getFoo()
if (bar == null) {
bar = getBoo()
}
if (bar == null) {
bar = getBaz()
}
return bar;

Categories