what even is

programming

what even is

functional programming

imperative programming

  • describe algorithms by writing instructions for the compiler
  • order of execution is important
  • usually need to store state
  • loops, conditionals, function calls
function getItemsByMemberName(memberName) {
    return fetchData()
        .then(function(data) {
            return data.items
        })
        .then(function(items) {
            var results = []

            for (var i = 0; i < items.length; i++) {
                if (items[i].member === memberName) {
                    results.push(items[i])
                }
            }

            return results
        })
        .then(function(items) {
            return items.sort(function(first, second) {
                return first.date - second.date
            })
        })
}

functional programming

  • describe algorithms by composing and piping functions
  • order of execution not important
  • no state
  • function calls, recursion
function getItemsByMemberName(memberName) {
    return fetchData()
        .then(get('items'))
        .then(filter(propMatches('member', memberName)))
        .then(sortBy(get('date')))
}

but why is that better

what is even going on here

small, generic, reusable functions

function get(prop, obj) {
    return obj[prop]
}

function propMatches(prop, match, obj) {
    return obj[prop] === match
}

function filter(fn, arr) {
    return arr.filter(fn)
}

function sortBy(fn, arr) {
    return arr.sort(fn)
}

small, generic, reusable functions

  • easy to test
  • easy to reason about
  • simple to compose into larger functions/systems
  • use a library like lodash/ramda -> simpler application code

no state

  • easier to hold parts of the system in your head
  • everything is deterministic
  • fewer moving parts
  • fewer bugs*

*anecdotally

why are you telling me this

what if i told you

we could write code

which uses some of these concepts

without any significant changes

var x = 0

function calculateX() {
    x = 10
}

function useX() {
    if (x >= 10) {
        // ...
    }
}


// Don't write out instructions which rely on state
calculateX()
useX()
function calculateX() {
    return 10
}

function useX(x) {
    if (x >= 10) {
        // ...
    }
}


// Pass values around instead
useX(calculateX())
var arr = [1, 2, 3, 4]
var evens = []
var doubles = []

// Try to avoid imperative constructs
for (var i; i < arr.length; i++) {
    if (arr[i] % 2 === 0) {
        evens.push(arr[i])
    }
}

for (var i; i < arr.length; i++) {
    doubles.push(arr[i] * 2)
}
var arr = [1, 2, 3, 4]

// Prefer functions like filter and map instead
var evens = arr.filter(function(x) {
    return x % 2 === 0
})

var doubles = arr.map(function(x) {
    return x * 2
})

what is programming

By Joseph Wynn

what is programming

  • 1,684