functional vs. imperative programming

Michael Scoggins

Michael Scoggins |


10/25/2020

functional vs. imperative programming

these are 2 sides to the same coin. in order for a program to be a program, it must contain an executable set of instructions. that is imperative programming: telling the computer what to do step by step (as in, it is imperative that you do this, and then do that). however, once you abstract that set of instructions and then name (declare) it — as some variable —it becomes a function that returns a value. you can now reuse that bit of code simply by calling it inside of other code, and you are using functional programming.

obviously, we would all prefer if there was already a function that did all the things we want the computer to do. but even telling the computer to run said function is itself imperative, so there is no escape from imperative programming.

however, it is best to write composable code, which implies using pure functions that always return the same value given the same arguments. this just makes it easier to build stuff without repeating ourselves constantly.

for example, instead of telling your robot every single step to go pick up your mail, as in:

  1. face door
  2. place hand on lock
  3. rotate lock counter-clockwise and move hand to knob
  4. rotate knob counter-clockwise and pull door open
  5. goto sidewalk and face east
  6. proceed 10 yards and stop
  7. etc.

you can just wrap all these instructions inside of getMail() and now you can type 9 characters whenever you want to fetch the mail. and if you want more flexibility, you can pass in variables as arguments. for example, getMail(house1, tuesday)where the first argument takes in a certain address and the second argument takes in the day it should pick it up.