Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Let's get Functional

Let's get Functional

Ever tried functional languages ? Ever been annoyed that every time you see the same Fibonacci examples or yet another maths problem ?

So what can functional languages really teach us on our day to day life as Java devs ?
This talk will take some concrete examples and show you how some functional approaches will make your life easier.
We will see how we can try and bring functional and immutability to our "beloved" Android Java 7 and what this brings us.

Video of the presentation at Droidcon Berlin 2015 available here:
https://www.youtube.com/watch?v=B4qbQ1wGpNM

Benjamin AUGUSTIN

June 05, 2015
Tweet

More Decks by Benjamin AUGUSTIN

Other Decks in Programming

Transcript

  1. Let’s get Functional

    View Slide

  2. @Dorvaryn
    +BenjaminAugustin-Dorvaryn
    Dorvaryn
    Benjamin Augustin
    Android Software Craftsman

    View Slide

  3. What is Functional
    Programming ?

    View Slide

  4. “In computer science, functional programming is
    a programming paradigm that treats computation
    as the evaluation of mathematical functions and
    avoids changing-state and mutable data.”
    - Wikipedia contributors, 2015

    View Slide

  5. View Slide

  6. ● Less code
    ● Expressive code
    ● Small units
    What’s the point ?

    View Slide

  7. Focus on what not how

    View Slide

  8. Core concepts

    View Slide

  9. ● Not mutable, unchangeable, changeless
    ● Modification -> new value
    ● Safe to cache
    Immutability

    View Slide

  10. ● Same input -> Same output
    ● No side effect
    ● Referential transparency
    Pure functions

    View Slide

  11. View Slide

  12. ● Not a requirement but helps … a lot
    ● Building your domain
    ● Dealing with absence of data
    Strongly typed

    View Slide

  13. View Slide

  14. “I call it my billion-dollar mistake. It was
    the invention of the null reference in 1965.”
    - Sir Tony Hoare, 2009

    View Slide

  15. ● Null object
    ● Optional
    ● Mandatory
    Modeling absence

    View Slide

  16. View Slide

  17. You can use most common languages

    View Slide

  18. ● RxJava
    ● AutoValue
    ● Guava
    ● Or… Kotlin ?
    For java 7 and lower

    View Slide

  19. View Slide

  20. Kotlin Syntax
    fun aFunction(parameter: String): String {
    return parameter
    }
    fun highOrder(param: Int, func: (Int) -> Int): Int {
    return func(param)
    }
    val lambda = { x: Int, y: Int -> x + y }

    View Slide

  21. Let’s get Functional

    View Slide

  22. fun foo(words: Array): Map {
    val result = mapOf()
    for (word in words) {
    val value = result.get(word)
    if (value != null) {
    result.set(word, value + 1)
    } else {
    result.set(word, 1)
    }
    }
    return result
    }
    What does foo do ?

    View Slide

  23. View Slide

  24. fun foo(words: Array): List> {
    return words.groupBy {
    word -> word
    }.map {
    Pair(it.key, it.value.count())
    }
    }
    Can you tell now ?

    View Slide

  25. ● Code should be self explanatory
    ● Not just the method name
    ● Keep things concise
    Expressive code

    View Slide

  26. ● Get items occurring at least 3 times
    ● Sort by occurrences
    ● As a list of strings
    Extensible code

    View Slide

  27. fun mostFrequents(occurences: Array, threshold: Int):
    List {
    return countOccurences(occurences).filter {
    it.second > threshold
    }.sortedBy {
    it.second
    }.map {
    it.first
    }
    }
    Extended Code

    View Slide

  28. View Slide

  29. View Slide

  30. Focus on your data

    View Slide

  31. ● Article, Product, User...
    ● Value objects -> Immutable
    ● Lists of value objects
    What is your data ?

    View Slide

  32. ● Fetching a list of users
    ● Calculating the price of a basket
    ● Input List -> Output List
    What is your processing ?

    View Slide

  33. Think like shell
    #!/bin/bash
    for jpg; do
    png="${jpg%.jpg}.png"
    if convert "$jpg" jpg.to.png ;
    then
    mv jpg.to.png "$png"
    else
    echo 'error' >&2
    exit 1
    fi
    done
    echo all conversions successful
    exit 0
    du -h | grep M | sort -nr | head -15

    View Slide

  34. ● map, flatMap, filter, findAll, merge, zip…..
    ● first, last, find, fold..…
    ● Decompose your processing using those functions
    Functions upon lists

    View Slide

  35. ● Display the saved articles in a list
    ● Fetch the items in a basket requiring age check
    ● Any filtering logic -> list + filter
    Don’t trust me ?

    View Slide

  36. ● Get the total of a basket
    ● Find an item in a list
    ● Any list traversal logic -> list + fold
    Another one ?

    View Slide

  37. View Slide

  38. ● f(x,y) applied on each element in a list
    ● x element in list
    ● y accumulator
    Fold ?

    View Slide

  39. Fold ?

    View Slide

  40. Maximum using fold
    +
    +
    +
    ->
    ->
    ->

    View Slide

  41. View Slide

  42. Basket example

    View Slide

  43. data class Basket(val items: List)
    data class Item(val barcode: String, val price: Double)

    View Slide

  44. data class Basket(val items: List)
    data class Item(val barcode: String, val price: Double)
    fun calculateBasket(basket: Basket): Double {
    var total = 0.0
    for (item in basket.items) {
    total = total + item.price
    }
    return total
    }

    View Slide

  45. data class Basket(val items: List)
    data class Item(val barcode: String, val price: Double)
    fun calculateBasket(basket: Basket): Double {
    return basket.items
    .fold(0.0, { total, item -> total + item.price })
    }

    View Slide

  46. data class Basket(val items: List)
    data class Item(val barcode: String, val price: Double)
    fun calculateBasket(basket: Basket): Double {
    return basket.items
    .fold(0.0, sum())
    }
    private fun sum() = {
    total:Double, item: Item -> total + item.price
    }

    View Slide

  47. data class Basket(val items: List)
    data class Item(val barcode: String, val price: Double)
    fun calculateBasket(basket: Basket): Double {
    var total = 0.0
    for (item in basket.items) {
    total = sum(item, total)
    }
    return total
    }
    private fun sum(item: Item, total: Double) = {
    total + item.price
    }

    View Slide

  48. data class Basket(val items: List)
    data class Item(val barcode: String, val price: Double)
    fun calculateBasket(basket: Basket): Double {
    return basket.items
    .fold(0.0, sum())
    }
    private fun sum() = {
    total:Double, item: Item -> total + item.price
    }

    View Slide

  49. View Slide

  50. View Slide

  51. View Slide

  52. Make your data immutable
    Start small
    Aim for pure functions
    Validate your data
    Focus on what not how

    View Slide

  53. Learn a functional language
    Keep learning
    Spend some time on pet projects
    Have fun !

    View Slide

  54. View Slide

  55. View Slide

  56. ● Learn you a Haskell for great good by Miran Lipovača
    ● Functional Programming in Java by Venkat Subramaniam
    ● Category Theory for Programmers by Bartosz Milewski
    Good reads

    View Slide

  57. Questions ?

    View Slide

  58. @Dorvaryn
    +BenjaminAugustin-Dorvaryn
    Dorvaryn
    Benjamin Augustin
    Android Software Craftsman

    View Slide

  59. Click to add body
    Click to add code

    View Slide