Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a benefit to storing an object in a variable before calling a method on it?

Example 1:

SomeObject someObject = new SomeObject();
if (someObject.Method())
{
    //do stuff
}
//someObject is never used again

vs

Example 2:

if (new SomeObject().Method())
{
    //do stuff
}

Is there any benefit to using the first method over the second, or vice versa?

like image 630
Ryan Kohn Avatar asked Jun 18 '10 20:06

Ryan Kohn


People also ask

What must happen before you can assign a value to a variable in Java?

You MUST place an initial value into such a "constant" variable. If you do not place this initial value, Java will never let you assign a value at a later time because you cannot do anything to change the value of a final (constant) variable.

Can you store a method in a variable Java?

Calling a Method With a Return Value A return value by itself would not be very useful, given that it does not print to the console. Fortunately, we can store a method's return value into a variable.

What is the necessity of reference variable in Java?

Reference variable is used to point object/values. 2. Classes, interfaces, arrays, enumerations, and, annotations are reference types in Java. Reference variables hold the objects/values of reference types in Java.

Can we store function in variable?

Functions stored in variables do not need function names. They are always invoked (called) using the variable name. The function above ends with a semicolon because it is a part of an executable statement.


1 Answers

There are at least three potential benefits:

  1. Readability: the first is more obvious in many cases than the syntax of the second example, especially to newer developers.

  2. Better debugging experience: If the constructor for SomeObject throws an exception, in the first case, the debugger will break on that line. In the second case, it's not obvious whether the exception is in the constructor or the method. The same issue arises for setting break points and inspecting values on the object - this will be difficult in the second case, and require setting the break point inside of the method.

  3. In the first case, you can use the object outside of that single call. If you really only need a method for a single call, and don't need the object reference, then a static method may be more appropriate.

like image 100
Reed Copsey Avatar answered Nov 06 '22 15:11

Reed Copsey