0

I've got a style question. It's something I've been doing since forever, but I can't figure out why, exactly.

In most languages I've used, you can call a method that returns a value as an argument to another method:

foo(bar())

which is equal to

var bar=bar()
foo(bar)

For some reason, the latter seems unsavory. Why is that? Is the first more readable, efficient, or clean?

whiterook6
  • 3,270
  • 3
  • 34
  • 77
  • Sorry about the duplicate. I tried some searches to see if something was already there but clearly didn't look hard enough. :[ – whiterook6 May 31 '13 at 16:45

2 Answers2

1

It's not necessarily equal.

foo(bar());

means "call bar and pipe its arguments to foo"

var retBar = bar();
foo(retBar);

means "initalize retBar, then call bar, store whatever it returns to retBar, and then call foo with retBar as its argumnet."

Depending on how expensive variables are to declare, the latter may have a larger memory footprint or slower runtime.

Really, though, it's an entire extra statement -- two extra statements, actually, depending on language -- and it leaves your code less clean. The only time I do method #2 is when I have some reason to use bar()'s value, even if only to peek at it in a debugger.

DougM
  • 2,808
  • 17
  • 14
0

I feel its a blend of all what you said. The former construct is favorable since

a. It prevent the declaration of an additional variable to achieve the same result.

b. Its more cleaner since its more easier to read/ understand

var accountBalance = sum ( principalAmount + calculateInterest() )

than

var varCalculateInterest = calculateInterest();

var accountBalance = sum ( principalAmount + calculateInterest() )

c. If you use features like recursion, you obviously will try the former. You will need a lot of temp variables to store the intermediate results. Please see an example below.

return concatenate(quicksort(less), pivot', quicksort(greater))

balumohan
  • 51
  • 1
  • 6