if you have any suggestions on how to modify the question title in order to be more descriptive, please feel free to say so .
Suppose you have a class method that returns an Object, is there a best practice or standard way of where to create the object within the method ? To clarify, see below :
public MyCustomObject myMethod(String arg1, String arg2){
try{
if (something){
...
} else {
...
}
} catch ( SomeException e ){
...
} catch ( SomeOtherException e ){
...
}
return myCustomObject;
}
MyCustomObject has an empty constructor, a constructor with 5 fields and getters/setters. I need to return a valid MyCustomObject in every case of the (simplified) flow above. Please do not focus on the control flow itself.
I think that I can either :
a) Initialize a variable of type MyCustomObject with null in the beginning of the method. Assign a new MyCustomObject to it for every different case in the control flow. Return it in the end.
b) Instantiate a MyCustomObject in the beginning by using the empty constructor. Modify the object with the setters for each of the cases in the flow.
Can you think of reasons why one of the above or a different way is preferable ?
Thanks
I prefer option 3 which you didn’t mention: Create a new MyCustomObject for every different case in the control flow, and return it immediately. No variable required, usually:
This usually ends up with less nesting, and it’s easier to read, in that as soon as you hit the
returnstatement, you’re done.Some people hold on to the dogma of only having a single exit point, but I regard that as somewhat pointless these days – it made sense in languages where you needed to do clean-up before returning, but with garbage collection and
finallyblocks for other resource clean-up, it’s unnecessary.If you return as soon as you can, you can often end up with less nesting within the code – which greatly increases readability.