The Functional Style

The functional style of programming has been around for a very long time, although it hasn’t been the mainstream. In recent years, it’s been gaining in popularity. Let’s first look at what it is, and then why that’s significant.

What’s the functional style?

“Computers are stupid; you have to tell them every detail,” were the words of my teenager learning to program. Sadly, feeling that pain every single day is the job of most professional programmers. Anything that can alleviate those troubles is a step in the right direction. Functional programming is one such solution.

In the imperative style of programming, we have to key in every step. Create a variable named i, set the initial value to 0, check if the value is less than k—wait, is it less than or less than or equal to? Hmm.

The declarative style is where you say what you want and let the functions you call figure out how to do it. For example, to find if our friend Nemo exists in a list of names, the imperative style will demand iterating over each element to compare the values at each position in the collection. In the declarative style, we’ll call a contains() method and be done quickly.

“How does that method work?” is a reasonable question. The short answer is “We don’t care,” but that sounds rather rude—let’s rephrase: “It’s encapsulated,” meaning we shouldn’t care. But as programmers, we know that such details are important.

The difference is that in the imperative style, the details are in your face all the time, whether you need them or not. In the declarative style, they are encapsulated in a layer below. You can seek the details, at your will, anytime you deem it important and not be bothered at other times.

Functional style builds on declarative style. It mixes the expressive nature of the declarative style with higher-order functions. We’re used to passing objects to functions and returning objects from functions. Higher-order functions may receive functions as parameters and/or may return functions as a result. We can nicely compose a chain of function calls—known as functional composition—to accomplish tasks, and that leads to fluent and easier-to-understand code.

The imperative style is familiar to most programmers, but it can get complex and hard to read. Part of the reason is that it contains too many moving parts. The following small example illustrates that point.

Get hands-on with 1400+ tech skills courses.