Sunday, September 2, 2012

Imperative vs functional programming style (Part I)

In computer science,  functional programming is a programming paradigm that treats computation as the evaluation of mathematical functions and avoids state and mutable data

Imperative programming, on the other hand, is a programming paradigm that describes computation in terms of statements that change a program state.

As an example we could would write a program that helps us pick the most popular song by U2 that is longer than 5 minutes.

Let's try it using Spotify's Web API. First, we declare the base functions that we're going to use for our example.

Next, let's write an imperative program that finds the song using those functions.

Using this programming style we mutate state using a series of steps until we get the desired result.

An alternative to this, rather messy, approach is to not mutate any state. Instead, the state goes through transformations as it flows through the composed functions.

Here it is.

Using this style, there's some copy overhead but the code is much more concise, easier to read and...beautiful?

Use the style that works best for you but be aware of the choices. If you are stuck with Java then Lambdaj might  help you accomplish something similar to the above code.

Btw, U2's most popular track that is longer than 5 minutes is Magnificent.

No comments:

Post a Comment