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


fun isValidAccount(accountNumber: String): Boolean {
// function logic
}

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


data class Customer(val name: String, val email: String, val country: String)

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.

6 thoughts on “Refactoring to Functional–Getting Started

  1. 'Hurricane Rob' (@RobAshton)

    Technically I was born and raised in the Isle of Man which is not part of the UK – but I’ll let that slide because I barely understand the political borders and boundaries in the British Isles or whatever it is called and neither do any of the forms I have to fill in on the internet.

    Will be following this series with some interest.

    Reply
  2. Pingback: Refactoring to Functional – Getting Started | Enjoying The Moment

  3. Pingback: The Morning Brew - Chris Alcock » The Morning Brew #1463

  4. mhshams

    Hi Hadi, Thanks for this sharing.

    A feedback about “immutability” in Kotlin:

    Given: class Foo(var x: Int)
    And: data class Bar(val foo: Foo)

    Even though “foo” is final in “Bar” but its property “x” can change. therefore “Bar” is not immutable. So turning all properties to final (“val”), does not guarantee object immutability.

    I think, it would be great if there was a specific way to define immutable objects in Kotlin. one way could be by an annotation, for example:

    [immutable] data class X(val y: Y, val z: Z)

    compiler then could check in classes that are annotated as “immutable”:
    1. all properties must be final (“val”)
    2. all properties must be immutable too.

    Reply

Leave a comment