What are the pros and cons of each option, considering long-term implications (increasing the number of functions / parameters, other developers taking over, etc.)?
Option 1: removes the need to pass foo
and bar
to each method, but will create nested functions that are hard to follow.
const myFunction = ({foo, bar}) => {
const results = []
const function1 = () => {
return foo + bar;
}
const function2 = () => {
return foo * bar;
}
const res1 = function1();
const res2 = function2();
results.push(res1, res2);
return results;
}
Option 2: you pass the parameters to each function, but remove the nesting, which in my opinion makes it more readable.
const function1 = ({foo, bar}) => {
return foo + bar;
}
const function2 = ({foo, bar}) => {
return foo * bar;
}
const myFunction = ({foo, bar}) => {
const results = []
const res1 = function1({foo, bar});
const res2 = function2({foo, bar});
results.push(res1, res2);
return results;
}
I would prefer to know how to improve my functional approaches here. Thank you!
The second approach is more idiomatic. In fact, the second approach has a name in functional programming. A function which takes in a shared static value as an input, a.k.a. an environment, is known as a reader.
In the above example, we define
function1
,function2
, andmyFunction
using the monadic notation. Note thatmyFunction
doesn't explicitly take the environment as an input. It also doesn't explicitly pass the environment tofunction1
andfunction2
. All of this “plumbing” is handled by thepure
andbind
functions. We access the environment within the monadic context using theask
monadic action.However, the real advantage comes when we combine the
Reader
monad with other monads using theReaderT
monad transformer.Edit: You don't have to use the monadic notation if you don't want to. You could define
function1
,function2
, andmyFunction
as follows instead.The disadvantage is that now you're explicitly taking the environment as input and passing the environment to sub-computations. However, that's probably acceptable.
Edit: Here's yet another way to write this without using the monadic notation, but still using
ask
,pure
, andbind
.Note that the monadic notation using generators is just syntactic sugar for the above code.