flame1481
flame1481

Reputation: 23

Is there any disadvantage in saving output of a function to a val?

I have a function toFoo that merges two data types: bar and baz. Is there any harm in doing the following?

val foo = toFoo(bar, baz)

serve(foo)

the val foo is not used in any other code. Is it more efficient to do the following instead? What is the difference?

serve(toFoo(bar, baz))

Am I using less memory in the 2nd snippet since im not saving anything to val foo?

Upvotes: 0

Views: 128

Answers (1)

Dima
Dima

Reputation: 40500

Efficiency doesn't matter here at all (assignments are rather cheap, and this one will most probably just be optimized away anyhow), and you would not be using any more (heap) memory, because you are only assigning a reference, and local variables live on the stack, so it is a question of style/taste and readability.

Someone mentioned in the comments that intermediate variables make the code more readable. I think, it is really the opposite of that. Especially, when a function is rather long and has complicated logic, having many one-time-use variables just clutters the view and makes the reader waste cycles on tracking them all.

My rule of thumb is to only assign a value to a variable if you are going to use it more than once. There are exceptional use cases, and special constructs (like for-comprehension) when it makes sense to assign every statement to a variable, but most of the time, I wouldn't do it.

Take a look at ChainingOps. There are two functions there - tap and pipe – that lots of pre-2.13 codebases used to just implement on their own in order to handle cases exactly like your example. They let you do things like this:

import scala.util.chaining._
toFoo(bar, baz).pipe(serve)

Or, maybe:

import scala.util.chaining._
toFooBar(bar, baz)
  .tap(log.info("Foobar: " + _))
  .pipe(serve)

I would say this makes the code more readable, then the "traditional way", because it explicitly outlines your intent as a single chain of transformations.

This question should really be closed, because it is totally opinion based though :)

Upvotes: 1

Related Questions