There is a subtle difference between the two snippets, but only when viewed within their scope. Consider them within methods:
public void doSomething1() {
new Something().method();
doSomeLongRunningSomething();
}
public void doSomething2() {
Something tmpSomething = new Something();
tmpSomething.method();
doSomeLongRunningSomething();
}
In the first method, the 'something' is immediately available for garbage collection while in the second method, tmpSomething
stays within scope during the run of doSomeLongRunningSomething
. If you are doing anything interesting during the finalize
(e.g. closing the file), this could introduce some quirks.
That said, my preference is for the second example and naming the new instance as it assists the debugging processing. While stepping through code you have a named instance that is easier to watch. That doesn't apply when you're getting pre-existing instances in which case I find chaining methods more readable, e.g. myDog.getEyes().getLeftEye().getColorAsRgb().getRed()
.