Procedural vs Object Oriented vs Functional Programming

So I've gone on about cool functional programming stuff like map, filter, and reduce. I've explained currying and closures.

But I've not really explained what functional programming is and why you should care about it. This post is part of a series that should explain why I think the functional approach is super neato and why I think you should try it.

First, let's compare functional programming with procedural and object-oriented programming.

Procedural Programming

Procedural programming is all about writing instructions for the computer. It's for loops, while loops, case statements, functions/sub-routines, and one instruction executed after another.

It's the basic stuff most of us know:

var a = 1  
var b = 2  
console.log(a + b)  
for(var i = 0; i < 10; i++) {  
    console.log(i)
}

The fundamental building blocks of procedural programming are instructions.

Object-Oriented Programming

Object-oriented programming, as it's practiced by most developers, is pretty much like procedural programming, but it encapsulates data and behavior into objects.

function make_dog(name) {  
    return {
        name: name,
        bark: function () {
            console.log('woof')
        }
    }
}

var wuffles = make_dog('wuffles')  
wuffles.bark()  

Object-oriented programmers can also define hierarchies of types and subtypes. This is meant to help with code reuse.

function make_st_bernard(name) {  
    var st_bernard = make_dog(name)
    st_bernard.bark = () => console.log('WOOF')
    return st_bernard
}

function make_chiwawa(name) {  
    var chiwawa = make_dog(name)
    chiwawa.bark = () => console.log('yipe yipe!')
    return chiwawa
}

In other languages types (or classes) even allow you use type resolution in your program's logic as an alternative to if-else blocks or case statements. This is called polymorphism.

The fundamental building blocks of object-oriented programming are types and objects.

Functional Programming

Functional programming is different. In functional programs, data passes through your code like water through a pipe (from function to function to function) to get a result.

Also, functions are treated as data to be worked on just like anything else in our program. We can take functions as a parameter, return them, build custom functions, and build functions from other functions.

The fundamental building blocks of functional programming are functions.

Functional programming also has some interesting restrictions. Namely that functions should be pure, they should avoid side effects, and data should be immutable.

What does that all mean? I'll tell you more about it next time. :)

Looking for a software developer?