Pure function


What is a pure function? What are its advantages? Why include logic in a pure function is awsome?

The answers you will find in this post.

The story. You, as a perfectionist developer, are wandering how to simplify the following class

class Calculator {
  int result = 0;
  void sum (int a, int b) {
    this.result = a + b;
    saveToDb (this.result);
  }
}

and testing, that is not very easy:

Calculator calculator = new Calculator ();
calculator.sum (4, 5);
int result = getDBDriver().executeQuery("select result").getResult();

You you feel that it could be better, but have no idea what is wrong. It’s look like a diamond compared to other large and messy, complex methods. Why bothering with this small thing? Ah yes, you are a perfectionist.

You read Pass all parameters to function post and … turned out everything is perfectly fine. The function gets all needed parameters. So what is wrong?

Ok. I’ll share a secret, a simple trick – use the ‘static’ keyword!

Static keyword? How could this help?

Let’s see:

class Calculator {
  int result = 0;
  static void sum (int a, int b) {
    this.result = a + b; //compiler error - java: non-static variable .. 
    saveToDb (this.result); //compiler error
  }
}

Oh no, errors.

Do not be afraid. We need to fix them. The problematic elements should be moved to another method:

class Calculator {
  int result = 0;
  void sum_ElementsThatsCauseAProblemWhenStatic (int a, int b) {
    this.result = sumStatic (a, b);
    saveToDb (this.result);
  }
  ...
}

and what’s left?:

  static int sum (int a, int b) {
    return a + b;
  }

Woow. Pure logic!

Amazing. It is a pure function – it takes the input, processes it, and returns the output, and no interaction with class state/fields or non-pure methods.

And now another magic happens – testing:

Assert.equals(5, Calulator.sum (2,3))

That’s it. Purity in every detail.

Summary

Extracting the logic to static methods/pure functions brings a lot of benefits: clarity, simplicity, easy testing and more. So, use them wherever possible.

I know that real projects are not as simple as our example, but I am showing the way and the benefits of using pure functions.

,

Leave a Reply

Your email address will not be published. Required fields are marked *