DEV Community

loading...
Cover image for Explaining: Pure Functions

Explaining: Pure Functions

Sean
Hi, name's Sean.
・2 min read

Intro

Have you ever heard that your code is poorly written, or that I won't work under different circumstances. That it requires lots of special handling that isn't needed. Bad news: you're in a tough spot, good news: there's a way out.

Functional Programming, What Is It?

Functional Programming(FP) is programming that is composed of pure functions, absence of side affects, avoiding mutable data, and imperative like programming to build software.

You lost me.

Basically, programming that avoids things like http calls and whatnot to make side affects avoidable and make useful, predictable code so it can be used over and over without concern or issues.

Pure Functions

Pure Functions are basically the pinnacle and heart of functional programming.

What Does That Mean?

Pure Functions contain all the requirements for FP, this means that if you follow most of the guidelines for pure functions you'll be able to understand FP, but this post isn't about FP as much as it is about PF(I know I turned it around on you!).

How Are They Used?

Pure Functions have many practical uses. Automation is one place where they are key. The idea of automation already involves some of the ideology of pure functions. Continuous use with no side effects, and output only being determined by the input.

Uh... English please.

Simply, reusability, and the input being what determines the output. Here's an example, Drake hit it!

Okay, I understand most of what you're saying but what's a sid effect?

Here's a more professional explanation: In computer science, an operation, function or expression is said to have a side effect if it modifies some state variable value(s) outside its local environment, that is to say has an observable effect besides returning a value (the main effect) to the invoker of the operation.

I don't get it.

Go back to the Drake example. There you'll see that in the first example the actual list is mutated in the forEach method's parenthesis. The code uses the push method to change the contents of the list. That is kind of a side effect, because if I wanted the original list it would be lost. In the second example the map method is used to return a mutated version of the list, so the original isn't gone.

So a side effect is manipulating the data?

No, manipulating data is fine, that is precisely what functions are for. The problem is when you make irreversible changes to the data, that's why we avoid mutable data, not using it.

Okay, what's an example.

Most modules and libraries are a combination of pure functions made to be predictable and reusable. Not all are like that though.

That's That

Hope you learned something.

Discussion (0)

Forem Open with the Forem app