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:
- It forces you to think about the absence of a value
- It makes the code more understandable
- It makes PMD happy