When I was first learning how to program I was taught object-oriented programming, and therefore, I learned how to think about software with an object-oriented mindset. One day, I was watching an interview with Alan Kay on YouTube in which he made a statement:

Lisp is the most important idea in computer science.

Of course, at this point I had to figure out why he would say such a thing. As I was exploring Lisp, I stumbled upon functional programming. I’d heard the term before but I never really understood it. After all, the definition for functional programming on Wikipedia states:

In computer science, functional programming is a programming paradigm — a style of building the structure and elements of computer programs — that treats computation as the evaluation of mathematical functions and avoids changing-state and mutable data.

Okay, it’s a different paradigm than object-oriented programming. But mathematical functions? Do I need to learn Category Theory to use functional programming? How do I apply mathematical functions to my model objects and view controllers?

Attempting to learn functional programming through the object-oriented programming lens can feel very daunting. But I’d like to demystify functional programming a bit and show, using an example, how elegant functional programming is.

There are a lot of interesting reasons to learn functional programming. Among them:

Functional programming helps reduce the amount of state in our code

It makes our code more testable and easier to reason about

It makes our code more composable

I won’t try to argue that our code should be “all functional all the time”, but I will argue that all programmers should learn functional programming. Even if you continue writing object-oriented code, learning functional programming can influence the way you think about your object-oriented code.

Throughout the remainder of this article, I’d like to give a lite introduction to functional programming using a real world example — parsing a server JSON response into a model.

Note: Swift 4.0 introduces the Codable protocol to facilitate parsing JSON. This is still an instructive example since JSON parsing is something many mobile developers are intimately familiar with.

Real World Example: Parsing a JSON Response from a Server