Overcoming
Dys-Functional
Programming
Declan Whelan and Shawn Button
Deliver Agile 2019
Overcoming
Dys-Functional
Programming
Declan Whelan and Shawn Button
Deliver Agile 2019
Who We Are
Declan Whelan is a software developer and agile coach. He’s extremely
passionate about delivering better software.
Declan trains, coaches and mentors teams to build environments in which
they can truly succeed: open, supportive environments where everyone
brings their genius selves to work each day to deliver continuous value.
But to summarize Declan in just one line: He helps organizations build
valuable software. Period.
Shawn Button is an agile/lean coach and developer, who helps
individuals, teams, and enterprises adopt better ways of working.
He is an expert in agile development practices.
Shawn believes that any team can do great things—with the right
leadership, mentorship, and support. His passion is helping teams find
their full potential, while helping to transform the system they are in.
Shawn and Declan are part of Leanintuit, a group of passionate coaches who help
people and companies work in better ways. We offer many types of training and
coaching to help your company succeed. Find us at www.leanintuit.com
Agenda
• Quick Intro to some Functional Programming terms
• Using FP Without Changing Design (in low-level code)
• Using FP To Improve Existing Design
• Quick Glance into the Future
• Recap
What Is FP?
… computation as the evaluation of
mathematical functions [that avoids]
changing-state and mutable data.
- Wikipedia
Good News!
• You don’t have to learn Category Theory to use FP.
• You can start using FP in your existing code.
• A little FP can improve your existing code a lot.
• You will not have to relearn everything you already know.
Pure Function
! Returns the same result if given the same arguments
! No side effects
// pure function
const isActive = id => id.active
// not pure functions
const process = id => db.find(id).filter(isActive)
const write = rec => db.save(rec)
const inc = rec => rec.count++
const log = rec => console.log(rec)
Functions
First class: can be assigned to values
Higher order: can take or return another function
const inc = x => x + 1
const square = x => x * x
const doMath = (fn, x) => fn(x) // function as parameter
doMath(inc, 3) // 4
doMath(square, 4) // 16
const multiplyBy = a => b => a * b // returns a function
const triple = multiplyBy(3)
triple(4) // 12
Refactoring Code with FP
function lets() {
"code"
}
Refactor to Functional
! Replace loop with functional built-ins (map, filter, etc)
! Separate stages of algorithm
! Assign anonymous function to named value
! Replace stages with pipeline (function chaining)
! Use partial application to create domain functions
! Use functional library to solve common problems
! Replace pipeline with function composition
Simple Design
!Passes the tests
!Reveals intention
!No duplication
!Fewest elements
Simple Design
!Tested
!Clear
!D.R.Y.
!Succinct
Exercise
Does Simple Design apply to FP?
Tested YES
Pure functions are easy to test
Clear YES

Clarity focuses on clear names for functions, parameters and types.
Functional code is usually more declarative.

DRY YES



Duplication removal often focuses on extracting new functions
Succinct YES
Functions tend to be small and focused.
“Functional” things you’re likely doing already
Your function/method should:
! Take and return values
! Avoid mutating parameters
! Avoid re-assigning variables (e.g. final/const)
! Avoid returning null
! Avoid mutating shared state
Improving Your
Design with FP
Command Pattern
Execute different actions the same way and defer execution.
fun lets() {
"code"
}
Command Pattern
OO FP
interface Command {
fun execute() : Unit
}
class TurnOn(val light: Light) :

Command {
fun execute() = light.on()
}
TurnOn(light).execute()
typealias Command = (
() -> Unit
)


val turnOn: (Light) ->

Command = {
light -> { light.on() }
}
turnOn(light)()
Command Pattern
OO FP
interface Command {
fun() : Unit
}
class TurnOn(val light: Light) :

Command {
fun() = light.on()
}
TurnOn(light).()
typealias Command = (
() -> Unit
)


val turnOn: (Light) ->

Command = {
light -> { light.on() }
}
turnOn(light)()
Command Pattern
OO FP
Command {
() : Unit
}
TurnOn(light: Light) :

Command {
() = light.on()
}
TurnOn(light).()
Command = (
() -> Unit
)


turnOn: (Light) ->

Command = {
light -> { light.on() }
}
turnOn(light)()
Command Pattern in FP
Maps well to FP.
Just void functions that take no arguments.
Use closures to create these functions.
Pass objects/data to these closures.
State Pattern
Changes behaviour when state changes.
State Pattern
Changes behaviour when state changes.
fun lets() {
"code"
}
def lets do
"code"
end
Refactor State Pattern to FP
! Create a Result data object with original return value and Context
! Refactor outer method to take Context as a parameter and return a Result
! Move all state data to Context
! Move or inline methods in State classes so their is only one method
! Rename State interface to be the same as the State method
! Rename Context to State
! Extract State method to a function in outer scope
! Redefine State to hold a function rather than an object
! Change references to state class to their extracted functions
! Delete State classes and State interface
State Pattern Comparison
OO FP
Internal state
Mutable state
Methods with side effects
External state
Immutable state
Pure functions
State Pattern in FP
Immutable state and no side-effects are nice.
Adds complexity to callers to pass in state.
Need to think carefully about how to represent state.
Advanced: could use the State monad.
Patterns in FP
! OO patterns can be implemented with functions
! FP implementations can be simpler
! Objects are a mental construct that can introduce
accidental complexity
! Data moves from residing in objects to being captured in
closures
! FP reduces moving parts by just using functions and
data objects
Recap
Functional Languages
Have capabilities that are hard to get in hybrid languages.
E.g.:
! Immutability
! Currying
! Easy composition of functions
! Pattern matching
! Lazy evaluation
! Powerful type systems (e.g. algebraic types)
! Fancy ways to handle errors, “nulls”, async, branches
(monads)
Our Path to FP (1) (your mileage may vary)
Learn how to code in an FP way
• Get familiar with your language’s native higher-order
functions, such as Array filter, map, and reduce.
• Try to write mostly pure functions.
• Try out a functional library such as Ramda, Vavr, etc.
• Get used to passing around and composing functions.
• Try out partial application and currying to simplify your
code.
• Play with a functional language. We had fun with Elixir.
• Don’t be intimidated by the jargon. Remember when OO
terms were weird? We’ve found that FP concepts are
simple once you get over the initial hump.
Our Path to FP (2)
Design with patterns and implement pattern with FP
• Refactor outside-in using TDD and safe refactorings.
• When you recognize a Command or State pattern use
what you learned here.
• Google how to approach other patterns in an FP way.
There are some people writing on this topic.
• Just try it!

Our Path to FP (3)
Design in an FP way
• See computation as the transformation of typed data.
• Consider data types carefully. You want to avoid a
series of tightly coupled functions that all depend on the
previous in the chain.
• Try applying all this to a new microservice
Traps We Fell Into
• Grouping of functions. No calling “on this” was confusing.
• Tightly coupled functions - output of one is input of next.
• Over-use of FP libraries can obfuscate your code.
• Trying too hard to shoe-horn everything into FP structures.
Maybe a for loop is okay until you get more fluent.
Challenges Doing This With A Team
• Requires a new way of thinking
• Terminology can be intimidating
• Skills not as common, so having entire team fluent might
be difficult
• Not a magic bullet - you can write bad code in any
paradigm
Good News!
• You don’t have to learn Category Theory to use FP.
• You can start using FP in your existing code.
• A little FP can improve your existing code a lot.
• You will not have to relearn everything you already know.
Overcoming
Dys-Functional
Programming
Declan Whelan and Shawn Button
Deliver Agile 2019
Photo Credits
Slightly Closed Macbook - Dmitry Chernyshov on Unsplash
Blue cell photo - http://www.publicdomainfiles.com/show_file.php?id=13940880015619
Connected Neurons - https://www.maxpixel.net/Neuron-Brain-Nervous-System-Neurons-Nerve-Cell-2213009
Neuron System - https://pixabay.com/photos/nerves-network-nervous-system-line-2728138/
Architectural Patterns
! Reactive Programming
! Message-driven
! Observables
Error Handling
! There are very elegant ways to handle errors
in FP.
! Including Either and Option monads.
Isolation of State
•Isolate to corners of app
•Move to stack/framework/language
•Declan to tweak
What are Some Benefits?
•Testability
•Debugging
•Concurrency
•More elegant way of solving some
problems
Immutability
•Avoid changing data, as this can have side
effects elsewhere in your program
•Same as no side effects / avoid changing
state?
Characteristics of FP
•Pure functions
•First class / Higher order functions
•Minimize shared, mutable state
To do list
! Timeline - Shawn
! Print simple design sheets
! Make slides look the same
! Make slides look better
! State pattern
! Declan practice
! Delcan refactoring list slide
!

Fp for the oo programmer

  • 1.
  • 2.
  • 3.
    Who We Are DeclanWhelan is a software developer and agile coach. He’s extremely passionate about delivering better software. Declan trains, coaches and mentors teams to build environments in which they can truly succeed: open, supportive environments where everyone brings their genius selves to work each day to deliver continuous value. But to summarize Declan in just one line: He helps organizations build valuable software. Period. Shawn Button is an agile/lean coach and developer, who helps individuals, teams, and enterprises adopt better ways of working. He is an expert in agile development practices. Shawn believes that any team can do great things—with the right leadership, mentorship, and support. His passion is helping teams find their full potential, while helping to transform the system they are in. Shawn and Declan are part of Leanintuit, a group of passionate coaches who help people and companies work in better ways. We offer many types of training and coaching to help your company succeed. Find us at www.leanintuit.com
  • 4.
    Agenda • Quick Introto some Functional Programming terms • Using FP Without Changing Design (in low-level code) • Using FP To Improve Existing Design • Quick Glance into the Future • Recap
  • 5.
    What Is FP? …computation as the evaluation of mathematical functions [that avoids] changing-state and mutable data. - Wikipedia
  • 6.
    Good News! • Youdon’t have to learn Category Theory to use FP. • You can start using FP in your existing code. • A little FP can improve your existing code a lot. • You will not have to relearn everything you already know.
  • 7.
    Pure Function ! Returnsthe same result if given the same arguments ! No side effects // pure function const isActive = id => id.active // not pure functions const process = id => db.find(id).filter(isActive) const write = rec => db.save(rec) const inc = rec => rec.count++ const log = rec => console.log(rec)
  • 8.
    Functions First class: canbe assigned to values Higher order: can take or return another function const inc = x => x + 1 const square = x => x * x const doMath = (fn, x) => fn(x) // function as parameter doMath(inc, 3) // 4 doMath(square, 4) // 16 const multiplyBy = a => b => a * b // returns a function const triple = multiplyBy(3) triple(4) // 12
  • 9.
  • 10.
  • 11.
    Refactor to Functional !Replace loop with functional built-ins (map, filter, etc) ! Separate stages of algorithm ! Assign anonymous function to named value ! Replace stages with pipeline (function chaining) ! Use partial application to create domain functions ! Use functional library to solve common problems ! Replace pipeline with function composition
  • 12.
    Simple Design !Passes thetests !Reveals intention !No duplication !Fewest elements
  • 13.
  • 14.
  • 15.
    Does Simple Designapply to FP? Tested YES Pure functions are easy to test Clear YES
 Clarity focuses on clear names for functions, parameters and types. Functional code is usually more declarative.
 DRY YES
 
 Duplication removal often focuses on extracting new functions Succinct YES Functions tend to be small and focused.
  • 16.
    “Functional” things you’relikely doing already Your function/method should: ! Take and return values ! Avoid mutating parameters ! Avoid re-assigning variables (e.g. final/const) ! Avoid returning null ! Avoid mutating shared state
  • 17.
  • 18.
    Command Pattern Execute differentactions the same way and defer execution.
  • 19.
  • 20.
    Command Pattern OO FP interfaceCommand { fun execute() : Unit } class TurnOn(val light: Light) :
 Command { fun execute() = light.on() } TurnOn(light).execute() typealias Command = ( () -> Unit ) 
 val turnOn: (Light) ->
 Command = { light -> { light.on() } } turnOn(light)()
  • 21.
    Command Pattern OO FP interfaceCommand { fun() : Unit } class TurnOn(val light: Light) :
 Command { fun() = light.on() } TurnOn(light).() typealias Command = ( () -> Unit ) 
 val turnOn: (Light) ->
 Command = { light -> { light.on() } } turnOn(light)()
  • 22.
    Command Pattern OO FP Command{ () : Unit } TurnOn(light: Light) :
 Command { () = light.on() } TurnOn(light).() Command = ( () -> Unit ) 
 turnOn: (Light) ->
 Command = { light -> { light.on() } } turnOn(light)()
  • 23.
    Command Pattern inFP Maps well to FP. Just void functions that take no arguments. Use closures to create these functions. Pass objects/data to these closures.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
    Refactor State Patternto FP ! Create a Result data object with original return value and Context ! Refactor outer method to take Context as a parameter and return a Result ! Move all state data to Context ! Move or inline methods in State classes so their is only one method ! Rename State interface to be the same as the State method ! Rename Context to State ! Extract State method to a function in outer scope ! Redefine State to hold a function rather than an object ! Change references to state class to their extracted functions ! Delete State classes and State interface
  • 29.
    State Pattern Comparison OOFP Internal state Mutable state Methods with side effects External state Immutable state Pure functions
  • 30.
    State Pattern inFP Immutable state and no side-effects are nice. Adds complexity to callers to pass in state. Need to think carefully about how to represent state. Advanced: could use the State monad.
  • 31.
    Patterns in FP !OO patterns can be implemented with functions ! FP implementations can be simpler ! Objects are a mental construct that can introduce accidental complexity ! Data moves from residing in objects to being captured in closures ! FP reduces moving parts by just using functions and data objects
  • 32.
  • 33.
    Functional Languages Have capabilitiesthat are hard to get in hybrid languages. E.g.: ! Immutability ! Currying ! Easy composition of functions ! Pattern matching ! Lazy evaluation ! Powerful type systems (e.g. algebraic types) ! Fancy ways to handle errors, “nulls”, async, branches (monads)
  • 34.
    Our Path toFP (1) (your mileage may vary) Learn how to code in an FP way • Get familiar with your language’s native higher-order functions, such as Array filter, map, and reduce. • Try to write mostly pure functions. • Try out a functional library such as Ramda, Vavr, etc. • Get used to passing around and composing functions. • Try out partial application and currying to simplify your code. • Play with a functional language. We had fun with Elixir. • Don’t be intimidated by the jargon. Remember when OO terms were weird? We’ve found that FP concepts are simple once you get over the initial hump.
  • 35.
    Our Path toFP (2) Design with patterns and implement pattern with FP • Refactor outside-in using TDD and safe refactorings. • When you recognize a Command or State pattern use what you learned here. • Google how to approach other patterns in an FP way. There are some people writing on this topic. • Just try it!

  • 36.
    Our Path toFP (3) Design in an FP way • See computation as the transformation of typed data. • Consider data types carefully. You want to avoid a series of tightly coupled functions that all depend on the previous in the chain. • Try applying all this to a new microservice
  • 37.
    Traps We FellInto • Grouping of functions. No calling “on this” was confusing. • Tightly coupled functions - output of one is input of next. • Over-use of FP libraries can obfuscate your code. • Trying too hard to shoe-horn everything into FP structures. Maybe a for loop is okay until you get more fluent.
  • 38.
    Challenges Doing ThisWith A Team • Requires a new way of thinking • Terminology can be intimidating • Skills not as common, so having entire team fluent might be difficult • Not a magic bullet - you can write bad code in any paradigm
  • 39.
    Good News! • Youdon’t have to learn Category Theory to use FP. • You can start using FP in your existing code. • A little FP can improve your existing code a lot. • You will not have to relearn everything you already know.
  • 40.
  • 41.
    Photo Credits Slightly ClosedMacbook - Dmitry Chernyshov on Unsplash Blue cell photo - http://www.publicdomainfiles.com/show_file.php?id=13940880015619 Connected Neurons - https://www.maxpixel.net/Neuron-Brain-Nervous-System-Neurons-Nerve-Cell-2213009 Neuron System - https://pixabay.com/photos/nerves-network-nervous-system-line-2728138/
  • 42.
    Architectural Patterns ! ReactiveProgramming ! Message-driven ! Observables
  • 43.
    Error Handling ! Thereare very elegant ways to handle errors in FP. ! Including Either and Option monads.
  • 44.
    Isolation of State •Isolateto corners of app •Move to stack/framework/language •Declan to tweak
  • 45.
    What are SomeBenefits? •Testability •Debugging •Concurrency •More elegant way of solving some problems
  • 46.
    Immutability •Avoid changing data,as this can have side effects elsewhere in your program •Same as no side effects / avoid changing state?
  • 47.
    Characteristics of FP •Purefunctions •First class / Higher order functions •Minimize shared, mutable state
  • 48.
    To do list !Timeline - Shawn ! Print simple design sheets ! Make slides look the same ! Make slides look better ! State pattern ! Declan practice ! Delcan refactoring list slide !