Chapter 6. Functional Programming

Functional programming is a different approach to development than the heavily object oriented approach that we have focused on so far. Object oriented programming is a fantastic tool for solving a great number of problems but it has some issues. Parallel programming within an object oriented context is difficult as the state can be changed by various different threads with unknown side effects. Functional programming does not permit state or mutable variables. Functions act as primary building blocks in functional programming. Places where you might have used a variable in the past will now use a function.

Even in a single threaded program, functions can have side-effects that change global state. This means that, when calling an unknown function, it can alter the whole flow of the program. This makes debugging a program quite difficult.

JavaScript is not a functional programming language but we can still apply some functional principles to our code. We'll look at a number of patterns in the functional space:

  • Function passing
  • Filters and pipes
  • Accumulators
  • Memoization
  • Immutability
  • Lazy instantiation

Functional functions are side-effect-free

A core tenant of functional programming is that functions should not change state. Values local to the function may be set but nothing outside the function may change. This approach is very useful for making code more maintainable. There need no longer be any concern that passing an array into a function is going to play havoc with its contents. This is especially a concern when using libraries that are not under your control.

There is no mechanism within JavaScript to prevent you from changing global state. Instead you must rely on developers to write side-effect-free functions. This may be difficult or not, depending on the maturity of the team.

It may not be desirable to put all the code from your application into functions, but separating as much as possible is desirable. There is a pattern called command query separation that suggests that methods should fall into two categories. Either they are a function that reads a value or they are a command that sets a value. Never the twain should meet. Keeping methods categorized like this eases in debugging and in code reuse.

One of the consequences of side effect-free functions is that they can be called any number of times with the same inputs and the result will be the same. Furthermore, because there are no changes to state, calling the function many times will not cause any ill side effects, other than making it run slower.

..................Content has been hidden....................

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