DEV Community

Adam Crockett πŸŒ€
Adam Crockett πŸŒ€

Posted on

Pure functions are anti modules

I get this feeling of double standards when I write a pure function I remove it's dependencies, pass them in as params and then we can test them.

But what about all those imports I casually used to give this function it's abilities, is contra to pure functions?

Why didn't I pass in the imports into the function at call time, I could have. But then this would become unwieldy... Then as an all or nothing kind of guy, should I just call pure functions a falisy and move on?

Top comments (6)

Collapse
 
deciduously profile image
Ben Lovy

The function itself is still pure, even if your environment is not.

Collapse
 
adam_cyclones profile image
Adam Crockett πŸŒ€

Like a nun in a casino?

Collapse
 
deciduously profile image
Ben Lovy

precisely

Collapse
 
jwhenry3 profile image
Justin Henry

Keep in mind your pure functions should be slim on dependencies.
If you are passing a class or function to another function to execute it and use the return, just pass the return of the call to the outer function instead of having the inner pure function call it. This way you can easily test each unit rather than dealing with mocking dependencies.

I look at pure functions as a means to isolate behavior away from the application so you can make sure your processes are well built and fully covered without worrying about implementation details.

IE:

function doSomething(obj) {
    return obj.doSomethingElse() || false;
}
doSomething(obj);
Enter fullscreen mode Exit fullscreen mode

vs

function doSomething(result) {
    return result || false;
}
doSomething(obj.doSomethingElse());
Enter fullscreen mode Exit fullscreen mode
Collapse
 
lexlohr profile image
Alex Lohr

Two thoughts about that: a function is pure because of a lack of side effects; the same input will get you the same output every time. Nothing about that prohibits external dependencies.

Also, I have a (quite unexpected for me to say that) strong opinion against patterns being used just for the sake of using them, because patterns are used best as a good fit to a problem. Even if using an external package would break the pattern, if it does solve your problem in an elegant and maintainable way, go for it! You don't get extra points for adhering to obscure pattern definitions, but you get better code if you write it yourself.

Collapse
 
vonheikemen profile image
Heiker

I think the focus should be on the function call rather than its definition. If the call meets the requirements of a pure function then don't bother trying to adhere to weird rules.