user710818
user710818

Reputation: 24248

Is it better to chain method invocations or to introduce an intermediate variable?

E.g. 2 method invocations:

myMethod(getHtmlFileName());

or

String htmlFileName=getHtmlFileName();
myMethod(htmlFileName);

which is better way, exclude less typing in first case ?

Upvotes: 2

Views: 283

Answers (4)

Slav Pilus
Slav Pilus

Reputation: 367

It will probably depend on the context. If you are going to use htmlFileName variable elsewhere in you code block you probably what to store it local variable like (especially true for some heavy method calls) :

String htmlFileName=getHtmlFileName();
myMethod(htmlFileName);

if it is one-off call the

myMethod(getHtmlFileName());

is probably more elegant and easy to read.

Upvotes: 1

ecniv
ecniv

Reputation: 197

If you use the getHtmlFileName() returned value later on, and if the returned value is fixed, you will want to use the first form, i.e. assign a local variable and reuse it, and thereby avoid redundant calls / object creations.

Otherwise (e.g. if you only call the getHtmlFileName method once, you will want to use the first form which is more concise, and which avoid a useless local variable assignment, but there is no real harm if you still use the second form (e.g. for debugging).

Upvotes: 0

claesv
claesv

Reputation: 2113

The second approach would help you debug the return value of getHtmlFileName(), but other than that, neither approach is better than the other in an absolute sense. It's a matter of preference, and perhaps context, I would say. In this particular case I'd go for the first approach, but if you were combining several methods, I'd go for the second, for sake of readability, e.g.:

String first = firstMethod();
String second = secondMethod(first);
String third = thirdMethod(second);

rather than

thirdMethod(secondMethod(firstMethod()));

EDIT: As others have pointed out, if you're going to use the value in more than one place, then obviously you'd use the second approach and keep a reference to the value for later use.

Upvotes: 2

Juvanis
Juvanis

Reputation: 25950

If you are going to use a return value of a method in more than one place, storing it in a variable and using that variable in your code could be more practical, readable and easily debuggable rather than calling the method every time:

String htmlFileName = getHtmlFileName();
myMethod(htmlFileName);
....
myMethod(htmlFileName + "...");

Upvotes: 3

Related Questions