Imperative programming vs Functional programming – a Beginner’s approach Part 5: Optionals

1. Introduction

Computer programming is about solving problems and getting things done the right way. However, as a beginner, you don’t care how you do it as long as you get it done. It works so why bother tackling it in a completely different way after all?

I thought the same way when I first stumbled upon functional programming in Swift. I knew about functional programming languages like Haskell or Scala, but I was under the impression that they are only good for research at an academic level and have no practical value of any kind. So I approached it reluctantly at first and soon asked myself how I lived without it.

The biggest challenge you face when discovering new programming paradigms is changing the way you think. This can be scary at first because you are used to doing things in a certain way and now you suddenly feel overwhelmed. It takes time and patience to get used to anything new but it’s worth doing it in the long run – being able to choose the right technique for a certain problem is a skill that any software developer should have in his toolbox.

OK, enough talking – let’s see what functional programming is all about.

2. The imperative approach

Your task for this tutorial is an easy one: create a non optional array with the elements of an optional array. Before diving into coding, think how you would solve the problem and break it into steps. This is how I would do it:

  • create the initial array and populate it with default values;
  • create the new array;
  • loop through the original array and do three things for each iteration:
    • extract the current optional value from the array;
    • unwrap the value with optional binding;
    • add the unwrapped value to the new array if the binding succeeds;
  • print the new array to the console;

That’s it for the algorithm – let’s move on to the implementation.

3. The imperative implementation

Fire up Xcode and open a playground. Delete everything from it and add this line to kick things off:

let optionalArray:[Int?] = [0, nil, 1, nil]

This creates the initial constant optional array and assigns its default values.

Note: You can also use type inference to create the array like this:

let optionalArray = [0, Optional.None, 1, Optional.None]

Next create the new array:

var nonOptionalArray = [Int]()

This line creates a variable array of integers – it is variable because you are going to add values to it soon.

Now loop through the original array with the for in control flow statement:

for optionalValue in optionalArray {

}   

Note: There are many ways of looping in Swift – this is the best approach for arrays because it gives you access to the current value for each iteration.

There is only one thing you should do inside the for loop for each value of the array – unwrap it with conditional binding:

if let unwrappedValue = optionalValue {

}   

Note: You can also use guard instead of if and take the happy path approach instead (Download).

There is only one thing you should do with the unwrapped value if the binding succeeds – add it to the new array:

nonOptionalArray.append(value)

Finally, print the new array to the console:

print(nonOptionalArray, terminator: "")

Note: There are other ways to print to the console as well – this approach doesn’t print the newline “\n” character in the playground.

That’s it – let’s analyse the implementation.

4. The imperative implementation analysed

The imperative implementation focuses on how to solve the problem by dividing the task into clear simple steps. This approach is easy to understand but it adds boilerplate code. Functional programming to the rescue!

5. The functional approach

Functional programming focuses only on what needs to be done – filter the array in this case – and doesn’t care how you actually do it. The flatMap function does exactly this: it creates a non optional array with the elements of an optional array.

Note: You can read more about the flatMap function here.

Enough theory – let’s see the flatMap function in action!

6. The functional implementation

Add this line to the playground to get started:

let nonOptionalfArray = optionalArray.flatMap{$0}

The flatMap function uses a closure – a fancy word for anonymous function – as its parameter. The closure’s body is the rule that filters the elements of the optional array. The closure’s argument – $0 – is the array’s current value.

Note: The closure’s body can be written in many other ways in Swift – this is the simplest approach of all because it uses trailing closure syntax and shorthand argument names.

Now print the new array to the console:

print(nonOptionalfArray, terminator: "")

That’s it – it can’t get any simpler than that! Let’s analyse the implementation.

7. The functional implementation analysed

The functional implementation is straightforward – define the filtering rule in the closure and let the flatMap function do the rest – no more boilerplate code.

8. Imperative vs functional comparison

Imperative advantages:

  • clear steps
  • easy to understand

Imperative disadvantages:

  • boilerplate code

Functional advantages:

  • no boilerplate code
  • short and sweet

Functional disadvantages:

  • difficult to understand

9. Conclusion

Both paradigms have their pros and cons – feel free to try them both and choose the one that suits you best. Happy coding! 🙂

Note: All the code in this tutorial was tested in a playground in Xcode 7.1 and Swift 2.1 (Download).

Advertisements
Posted in Functional programming

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Enter your email address to receive notifications of new posts by email.

Simple Programmer
%d bloggers like this: