Question

I try to remove all PMD warnings in my project and have some difficulties. I have a method that returns a Container object. This was my original method (simplified):

try {
    return setResult();
} catch (Exception ex) {

}
return null;

PMD warned that there are 2 return statements. So I tried this:

Container result = null;
try {
    result = setResult();
} catch (Exception ex) {

}
return result;

=> PMD warned about initializing with null. So I tried this:

Container result;
try {
    result = setResult();
} catch (Exception ex) {

}
return result;

=> Eclipse did not compile this, suggesting to use the "= null" variation.

What am I missing here? How do I have to write this method without PMD warnings?

Was it helpful?

Solution

I'd use the second approach you show:

Container result = null;
try {
    result = setResult();
} catch (Exception ex) {

}
return result;

Because, as PMD points out, it is important to avoid unnecessary return statements for the purpose of reducing complexity.

The PMD documentation classifies the NullAssignment rule as "controversial". It's usefulness very much depends on the context. Here is the sample code they provide:

public void bar() {
  Object x = null; // this is OK
  x = new Object();
   // big, complex piece of code here
  x = null; // this is not required
   // big, complex piece of code here
}

So, unless you can assign the Container variable with a meaningful value beforehand - you should probably ignore this rule for this code fragment.

If you want to completely avoid the null assignment, you could use Guava's Optional. In this case it has the following advantages:

  1. It forces you to think about the absence of a value
  2. It makes the code more understandable
  3. It makes PMD happy
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top