Tag Archives: Functional Programming

Refactoring to Functional–Why Class?

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

In College

Teacher: We are surrounded by objects in the real world. These can be cars, houses, etc. That’s why it’s very easy to associate real world objects with classes in Object Oriented Programming.

2 weeks later

Jake: I’m having a bit of hard time with these objects. Can you give me some guidance?

Teacher: Sure. There’s actually a couple of more or less formal processes to help you, but to sum it up, look for nouns. And verbs are like methods that can be performed on the class. The behavior so to speak.

Jake: Well that seems reasonable. Thanks!

Jake graduates.

Jake’s on the job

Phil: Hey Jake. I’ve been looking at this class of yours. It’s a little bit too big.

Jake: Sorry. And what’s the issue with that?

Phil: Well, thing is. It’s got too many responsibilities. It does too much.

Jake: And?

Phil: Well think about it. If it does too much, it means that it touches many parts of the system. So the probability of having to touch the class when changing code is higher, which means more probability of breaking things. Plus, 1000 lines of code in a single class is harder to understand than 30 lines.

Jake: Yeah. Makes sense.

Phil: Break these up into smaller classes. That way each class does only one thing and one thing alone.

A year later

Mary: Jake, I’m just reviewing this class of yours, there’s not much behavior in it.

Jake: Yeah well I wasn’t sure if that behavior belonged in the Customer class or to the Accounts class, so I placed it in this other class called CustomerService.

Mary: OK. Fair enough. But the Customer class isn’t really a class anymore. It’s more a DTO.

Jake: DTO?

Mary: Yes, a Data Transfer Object. It’s like a class but without behavior.

Jake: So like a structure? A record?

Mary: Yes. Kind of. So just make sure your classes have behavior. Otherwise, they’re not really classes. They’re DTO’s.

Jake: OK.

2 years later

Mathew: Jake, looking at this class. It’s tightly coupled to a specific implementation.

Jake: Huh?

Mathew: Well, you’re creating an instance of Repository inside the Controller. How you going to test it?

Jake: Hmm. Fire up a demo database?

Mathew: No. What you need to do is first off, program to an interface not a class. That way you don’t depend on a specific implementation. Then, you need to use Dependency Injection to pass in a specific implementation, so that when you want to change the implementation you can.

Jake: Makes sense.

Mathew: And in production, you can use an IoC Container to wire up all instances of the different classes.

3 years later

Francis: Jake. You’re passing in too many dependencies into this class.

Jake: Yeah but the IoC Container handles that.

Francis: Yes. I know but just because it does, it doesn’t make it right. Your class is still tightly coupled to too many other classes (even though the implementations can vary). Try and keep it to 1 to 3 maximum.

Jake: OK. Makes sense. Thanks.

4 years later

Anna: Jake. This class, why did you name it Utils?

Jake: Well. I didn’t really know where to place that stuff cause I don’t know where it really belongs.

Anna: OK. It’s just that we already have a class for that. It’s called RandomStuff

Over a beer…

Jake: You know Pete, I’ve been thinking. They teach us that we need to think in terms of objects and identify these with nouns among other techniques. We then need to make sure that we name them correctly, that they’re small, that they only have a single responsibility and that they can’t have too many dependencies injected into them. And now they’re telling us that we should try and not maintain state because it’s bad for concurrency. I’m beginning to wonder, why the hell have classes at all?

Pete: Don’t be silly Jake. Where else are you going to put functions if you don’t have classes?

Pete: Another beer?

Until next time.

Refactoring to Functional– Reducing and Flattening Lists

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

In this part let’s pick up some more primitives of functional programming and see how we can use them. We’re going to expand the previous list of albums to also include track information

We’re going to solve two different exercises this time:

  1. Get a list of albums and their total duration.
  2. Get a list of tracks that are shorter than a certain length, along with the corresponding album title.

To get a list of albums and their total duration, we’ll go for the simplest approach, using some of the primitives we picked up in the previous part.

reducing to a single value

What we’re doing in the previous code is iterating through the list of tracks and summing them up. As expected, there’s a function for that: reduce. Reduce takes a list of items and returns a single value, applying a specific operation to the list.

Knowing this, we can refactor the code to use reduce.

reduce versus fold

Kotlin also provides a very commonly used function named fold which does the same thing as reduce. The difference between the two is that fold takes an explicit initial value, whereas reduce  uses the first element from the list as the initial value.

Dealing with trees

Up to now, we’ve used forEach, map, filter and reduce to perform operations on lists. The problem with trying to find a list of tracks that meet a certain criteria is that this list is a list inside another list, i.e. we have a tree, albeit a small one. Filtering the original list is not going to work since the information to filter is on a branch. We therefore need to filter out based on the branch.

Here’s a first attempt

What we’re doing is iterating through the list of albums, and then for each one, filtering out those that match a certain criteria. On each iteration we hold a reference using a closure to the current album, and then add those matching the criteria as a new pair to the result.

Once again we can avoid some of this manual work and delegate it to a function named flatMap that takes a list, applies a transformation to each item and returns a new list with these items.

With that, we can refactor the previous code to

There’s a more generic version of flatMap, named flatMapTo which allows us to specify the resulting collection.

Other constructs as they come

In addition to filtering results, we can also find out if an item on the list matches a certain predicate with any, or if all items match it with all and last but not least find the first item that matches it with find.

We can also group items of a list or zip two lists (combine items from each list into pairs into a new list) as well as perform a few more basic operations on lists. Hopefully with these constructs we’ll have enough to solve problems.

Until next time.

Refactoring to Functional– Basic Primitives

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

Say we have a list of great albums (i.e. Pink Floyd’s discography*)

We want to get a list of all albums that were number one in both the US and the UK.

The Imperative Approach

Let’s go for the simple approach. A for loop iterating the length of the list and adding the new items to another list.

This works and is simple enough. But there are a couple of issues, if we’re trying to abide by the functional paradigms highlighted in the previous post. In particular, treating things as infinite. Here we’re consciously aware of the length of the list.

Refactoring to infinite lists

We want to avoid having to deal with indices, lengths and counts and worrying whether we have some element in or out of bounds. So the first step is to refactor to remove the actual loop index. In Kotlin, there is a for in loop which allows us to iterate through anything that has an iterator() function. In other words, anything that implements Iterable<T>.

Now we no longer need to deal with lengths.

Adding some syntactic sugar

The previous is better, but we can add some syntactic sugar. Instead of explicitly having a for in we can use an extension function that Kotlin provides, forEach which does the same thing

Since we no longer have the actual album element we can reference the current item the iterator is on using the it reserved word in Kotlin.

What we want instead of how we want it

If we look at the previous code, what we’re doing is removing elements that don’t match a certain criteria. We’re doing this by creating another list and adding the ones that do match to this new list. But if we were to remove the name of the function, to understand what we’ve just described, we’d need to mentally envision it taking into account the for loop, the temporary list, etc.

Of course, with this code it isn’t that hard but add another embedded for loop and things can start to get ugly.

The problem here is that we’re telling the computer how we want something done, instead of what we want done. What we want is to filter a list. What we’ve done is create another list and copy items to it, then return that list. Why not instead just filter the list?

Refactoring to asking versus telling

In Kotlin there is a filter function that takes a list and returns a new one that matches a certain predicate.

We can therefore refactor the code to

The reason we’re omitting the parenthesis is that by convention in Kotlin, if the last parameter to a function is another function, we can omit these.

As a side-effect of this refactoring, we’ve also removed the temporary list, and while in the previous code, hits was declared as immutable, the list itself (declared as ArrayList) was mutable. Win?

Changing data types

What happens now if we need something slightly different? We’re not always bound to work with the same type of data. Let’s assume for instance we want to return the years where an album made it to number one in both the UK and the US. We could of course do the following

The problem is that we re-introduce again some of the issues we had previous, namely using a temporary variable and again telling the computer how we want something versus what we want.

Using Map to transform results

Much like filter, Kotlin offers another function to help us do this: map.

which takes a function that given an input of type T produces an output of type R, returning a list of R. We can therefore refactor the previous code to

Once again we’ve gone from saying how to do something to asking for it.

Basic Primitives

The two functions we’ve just used: map and filter are some of the main primitives in functional programming. With them we can start to treat lists as infinite, chain them and transform results to what we need without having to deal with for loops, lengths, indices or complicated loops. We’ll see if they actually do help dramatically as we start working on more complex scenarios.

Until next time.

*The true Pink Floyd.

Refactoring to Functional–Getting Started

This is a multi-part series on Refactoring to Functional Programming

  1. Getting Started
  2. Basic Primitives
  3. Reducing and Flattening Lists
  4. Why Class?

It’s high-time I improve my functional programming skills, and like my fellow countryman*, I’ll do it in the open. Different to Rob though, I’m going to use Kotlin, not Clojure. Reasons are:

  • I’m loving the language and am mostly comfortable with it.
  • I feel it’s a good stepping stone as it provides familiarity, allowing me to focus on functional paradigms.
  • Kotlin claims to have functional aspects. I’m hoping to prove this right.
  • It fits in nicely with my job.

and most importantly, because I want to.

In a series of posts, I’ll try and look at ways of solving problems using a functional approach as opposed to an imperative one. I’m not a big fan of blog post series, primarily because they require some sort of structure and planning, but this is an ongoing process and I’m not going to wait till the end to write about it. And while a certain level of structure will go into these posts, I can’t commit to how it will pan out so we’ll just pretend it’s not a series.

I want to give up-front credit to @jhusain as some of the ideas and exercises will be based on his LearnRX project as well as my friend Rob whose brain I pick, and will continue to pick with my functional insecurities. Last but not least also thanks to Andrey, who’ll undoubtedly (he doesn’t know yet) will end up doing some reviews.

Functional Programming

Wikipedia defines Functional Programming as

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 state and mutable data. Functional programming emphasizes functions that produce results that depend only on their inputs and not on the program state – i.e. pure mathematical functions. It is a declarative programming paradigm, which means programming is done with expressions.

The key ideas to keep in mind when doing functional programming are:

  1. Everything is a function
    As such we need to stop thinking about objects, classes, etc. other than for returning data or interop with the platform.
  2. Functions should be pure
    A pure function should always return the same output given the same input and should not depend on anything that is not directly the input (i.e. external data). It should also not cause any side-effects.
  3. We shouldn’t maintain state
    Shared state is the root of all evil. Or so they say. In any case, if we can’t really depend on state according to point 2, then why maintain it.
  4. We should consider input infinite
    Apparently it’s better, specially if we combine it with lazy evaluation. We’ll see the benefits at some point. Or at least I hope we do.

Benefits of Functional Programming

Seems there are many benefits to functional programming, including the ability to achieve concurrency more easily as state is not maintained, writing more concise code, and solving some problems which using OO paradigms might not be so straightforward.

But that’s what they say. I want to find out for myself. So until then, I’m going to take it all with a pinch of salt. Worse that can happen is that I end up looking at approaching problems in a different way, and that for me, is definitely a win.

We’ll see…

Kotlin as a functional language

Although Kotlin is far from being a purely functional language, it does have support for functions as first-class citizens and also allows for creating immutable data, so in principle it should suit our needs. If you’re coming from a Java or C# background, you’ll have little trouble getting used to Kotlin’s syntax. I already covered the basics of Kotlin in a four part series and while there have been some changes to the language, much of it remains the same. If you want to follow this series, you can use any flavor of IntelliJ or use the command line compiler with your favorite editor. But for heavens sake, if you choose the latter, let me not catch you using cursor keys.

Top-Level Functions

In Kotlin you can have a file and in the file declare any number of functions, much like you can with JavaScript. There’s no need for a static class or object. We can simply do something like

This function sits standalone, declared as part of a package, and can be used anywhere where the corresponding package is imported.

Immutable Data and Common Data Structures

Kotlin has shorthand for declaring properties on a class, be it a regular class or a data class (i.e. a DTO). When declaring properties we can either make them mutable (var) or immutable (val). To declare a data class with three immutable properties we could do

In addition to creating immutable data types, functional languages such as Clojure use a series of common well-known data structures, namely vectors, lists and maps, all of which are available in Kotlin and we’ll be using.

Until next time.

* I was born in Iran, raised in the UK till I was 10, and living in Spain ever since. Rob as far as I know was born and raised in the UK Isle of Man. Yet I feel a bond. Maybe it’s the Stilton cheese.