Groovy Functional Programming - Pure Functions

Functional programming and pure functions go hand in hand. When we program in functional style, it is recommended to write pure functions as much as possible. So what are pure functions?

A pure function is one which

  • Does not produce any side effects and
  • Does not depend on any side effects

Let us consider a few examples to understand this.

def getFileContent = { String path ->
	Paths.get(path).text
}
If you are not familiar with closures, this article provides the necessary details.

The above closure reads the contents of the text file whose path is passed as the argument, and returns the content of the file. Since this involves I/O, getFileContent is not pure.

@ToString
class Person {
    String name
    String age
}
def celebrateBirthday = { Person person ->
    ++person.age
}

Person kumar = new Person(name: 'Kumar', age: 23)
celebrateBirthday(kumar)
println kumar // Person(Kumar, 24)

Here the closure celebrateBirthday modifies the field age of the object of type Person. Hence celebrateBirthday is not pure.

def getNumber =  {
    def millis = System.currentTimeMillis()
    millis % 10
}

Even though getNumber does not mutate anything, it depends on the method currentTimeMillis of System class, which is not pure. Hence getNumber is not pure either.

def add = { number1, number2 ->
    number1 + number2
}

The closure add neither produces any side effects, nor depends on anything that causes a side effect. Hence add is pure.

Note that if you add a print statement inside add(Say, for debugging purpose), it is not pure anymore!

def add = { number1, number2 ->
    def sum = number1 + number2
    println "Sum is $sum" // not pure anymore
    sum
}