What is functional programming?

Functional programming is a paradigm (a style of structuring your programs). In essence, the focus is on transforming data with expressions (ideally such expressions should not have side effects). Its name, functional, is based on the concept of a mathematical function (not in sub-routines, methods, or procedures). A mathematical function defines a relation between a set of inputs and outputs. Each input has just one output. For example, given a function, f(x) = X2; f(5) is always 25.

The way to guarantee, in a programming language, that calling a function with a parameter always returns the same value, is to avoid accessing to mutable state:

fun f(x: Long) : Long { 
return x * x // no access to external state
}

The f function doesn't access any external state; therefore, calling f(5) will always return 25:

fun main(args: Array<String>) {
var i = 0

fun g(x: Long): Long {
return x * i // accessing mutable state
}

println(g(1)) //0
i++
println(g(1)) //1
i++
println(g(1)) //2
}

The g function, on the other hand, depends on mutable state and returns different values for the same.

Now, in a real-life program (a Content Management System (CMS), shopping cart, or chat), state changes. So, in a functional programming style, state management must be explicit and careful. The techniques to manage state change in functional programming will be covered later. 

A functional programming style will provide us with the following benefits:

  • Code is easy to read and test: Functions that don't depend on external mutable state are more accessible to reason about and to prove
  • State and side effects are carefully planned: Limiting state management to individual and specific places in our code makes it easy to maintain and refactor
  • Concurrency gets safer and more natural: No mutable state means that concurrency code needs less or no locks around your code
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.129.194.123