Search code examples
javareturn-valuedefault-value

Return a Document in a method


When returning an Object (as Document) in a method and creation isn't implements AutoCloseable I often see declaring first line the object and returning it at the end:

public Document myMethod() {
 Document document = null
 try {
    document  = docFactory.newDocumentBuilder().newDocument();
    //...work on document 
 } catch(Exception e) {
   // Handle Exception
 }
 return document;
}

It seems that the following rule is always correct, create and return inside try clause (and possible to extract this code to method )

public Document myMethod() {

 try {
    Document document  = docFactory.newDocumentBuilder().newDocument();
    //...work on document
    return document;
 } catch(Exception e) {
    // Handle Exception
 }
 return null;
}

Am I missing anything? (you can relate to cases where null can be a default value but it's less significant)


Solution

  • Having only a single return statement at the end of a method was once taught as a style guideline to promote readability. Perhaps merely out of habit, it is still my preference when working on projects that don't have an established style to the contrary.

    However, the only cases where it really makes a difference are long, complex methods that should probably be decomposed anyway.

    Given good coding practices (e.g. test appropriate unit test coverage, so you know you're returning the right thing under any relevant condition, including exceptions) this really is just a matter of team/project preference.