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

The Next Step is Functional

anildigital
February 27, 2015

The Next Step is Functional

Talk

anildigital

February 27, 2015
Tweet

More Decks by anildigital

Other Decks in Programming

Transcript

  1. • Object oriented developer for 7+ years
 • In the

    transformation to Functional Programming world
 • Loves to solve problems with clean & simple solutions
 • Always looks to solve core problem not symptoms
 • ♥ traveling & listening music About me
  2. • Walkthrough of SOLID design principles
 • SOLID to Functional

    Transformation
 • Why Functional Programming matters
 • SOLID vs FP comparison
 • Functional Principles for the object oriented developer
 • Where are we heading? Structure
  3. • Rigid - Difficult to change • Fragile - Easily

    breakable • Immobile - Reuse is impossible • Viscous - Toughness in preserving design Smells of bad design
  4. • Basic Object Oriented Programming principles
 • Makes programs easier

    to maintain & extend over time
 • Guidelines to remove code smells SOLID principles
  5. Single Responsibility • Each class or method should have single

    responsibility • There should be never more than one reason for a class to change • The responsibility should be encapsulated • Separation of concerns
  6. • Software entities (classes, modules, methods) should be open for

    extension, but closed for modification Open Closed Principle
  7. • Many client specific interfaces are better than one general

    purpose interface
 • Clients should not be forced on methods that they do not use Interface Segregation
  8. If you take the SOLID principles to their extremes, you

    arrive at something that makes Functional Programming look quite attractive.
  9. If you take the SOLID principles to their extremes, you

    arrive at something that makes Functional Programming look quite attractive. https://www.flickr.com/photos/kiedyszko/15310777905
  10. The venerable master Qc Na was walking with his student,

    Anton. 
 
 Hoping to prompt the master into a discussion, Anton said "Master, I have heard that objects are a very good thing - is this true?" 
 
 Qc Na looked pityingly at his student and replied, "Foolish pupil - objects are merely a poor man's closures." http://www.clipartpal.com/_thumbs/005/001/Business_Occupations/Religious/Monks/religion_buddhism_92898_tns.png
  11. Chastised, Anton took his leave from his master and returned

    to his cell, intent on studying closures. 
 
 He carefully read the entire "Lambda: The Ultimate..." series of papers and its cousins, and implemented a small Scheme interpreter with a closure-based object system. 
 
 He learned much, and looked forward to informing his master of his progress. http://www.clipartpal.com/_thumbs/005/001/Business_Occupations/Religious/Monks/religion_buddhism_92898_tns.png
  12. On his next walk with Qc Na, Anton attempted to

    impress his master by saying "Master, I have diligently studied the matter, and now understand that objects are truly a poor man's closures." 
 
 Qc Na responded by hitting Anton with his stick, saying "When will you learn? Closures are a poor man's object." At that moment, Anton became enlightened. - Anton van Straaten http://www.clipartpal.com/_thumbs/005/001/Business_Occupations/Religious/Monks/religion_buddhism_92898_tns.png
  13. http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 public class FileStore : IMessageQuery { private readonly

    DirectoryInfo workingDirectory; public FileStore(DirectoryInfo workingDirectory) { this.workingDirectory = workingDirectory; } public string Read(int id) { var path = Path.Combine( this.workingDirectory.FullName, id + ".txt"); return File.ReadAllText(path); } }

  14. FileStore class is a simple example of data with behaviour

    • The behaviour is Read method • The data (also sometimes known as state) is workingDirectory
  15. http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 Func<DirectoryInfo, int, string> read = (workingDirectory, id) =>

    { var path = Path.Combine(workingDirectory.FullName, id + ".txt"); return File.ReadAllText(path); };
  16. There is no data and you pass workingDirectory to it.

    
 This doesn’t look like object. And is just a simple function.
  17. http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 var workingDirectory = new DirectoryInfo(Environment.CurrentDirectory);
 
 Func<int, string>

    read = id => { var path = Path.Combine(workingDirectory.FullName, id + ".txt"); return File.ReadAllText(path); };
  18. It’s closure, because function closes over the outer variable workingDirectory.

    
 Effectively, the function captures the value of the outer variable.
  19. http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 [CompilerGenerated] private sealed class <>c__DisplayClass3 { public DirectoryInfo

    workingDirectory; public string <UseClosure>b__2(int id) { return File.ReadAllText( Path.Combine(this.workingDirectory.FullName, id + ".txt")); } }
  20. http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 Func<DirectoryInfo, int, string> read = (workingDirectory, id) =>

    { var path = Path.Combine(workingDirectory.FullName, id + ".txt"); return File.ReadAllText(path); }; var wd = new DirectoryInfo(Environment.CurrentDirectory); Func<int, string> r = id => read(wd, id); // Returns partial function r(42); r(99);

  21. http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 let workingDirectory = DirectoryInfo(Environment.CurrentDirectory) let read id =

    let path = Path.Combine(workingDirectory.FullName, id.ToString() + ".txt") File.ReadAllText(path)

  22. Notice how much less ceremony is involved. http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 let

    read (workingDirectory : DirectoryInfo) id = let path = Path.Combine(workingDirectory.FullName, id.ToString() + ".txt") File.ReadAllText(path) let wd = DirectoryInfo(Environment.CurrentDirectory) let r = read wd
 r(42)
  23. Object Oriented Style Client Component operation() add(Component) remove(Component) getChild(int) Leaf

    Composite operation() add(Component) remove(Component) getChild(int) Children operation() Problem broken into Object Oriented Parts
  24. Object Oriented Style Client Component operation() add(Component) remove(Component) getChild(int) operation()

    add(Component) remove(Component) getChild(int) Children Component show() Component show() Composite Button show()
  25. Functional Style md toHTML postProcess modifyDOM Functions are also composed

    together to form more behaviours. visit post addId genID composed of
  26. Why Functional programming? • Elegance • Purity • Avoid mistakes

    and easy debugging • Facilitates multithreaded programming / concurrency • Programming with values
  27. • Reduces code duplication • Allows better reuse • Improves

    code readability • Eliminates ugly programming by side-effects • It’s easy to maintain complex systems with singly responsible functions Why Functional programming?
  28. SOLID vs FP • Single Responsibility - A function which

    has no side effect. Values in Value out • A function therefore is by default can only have a single responsibility
  29. SOLID vs FP • Open Closed - A function can

    be extended using higher order functions. Functional composition. • Immutable object cannot be modified under creation • Safe to add additional behaviour • New pure functions can’t break existing functionality because it can’t change state. • Type classes
  30. SOLID vs FP • Liskov’s substitution principle (design by contract)

    • Doesn’t make much sense in FP • Type classes (co-variance contra-variance) kind of solve this.
  31. SOLID vs FP • Interface Segregation - What could be

    smaller interface than a function? • Structural subtyping (Ruby, OCaml, Go) • Java 8 Functional Interfaces • Use higher order functions instead of interfaces. • Type classes
  32. SOLID vs FP • Dependency Inversion - What easier to

    invert a dependency than higher order function • Higher order functions provide inversion of control • Passing typed parameters, rather than hardcoding a function to get value
  33. SOLID vs FP So what it boils down to. •

    Just use functions and higher order functions • SOLID Principles followed by default in FP
  34. Function Properties • Functions are deterministic • You always get

    same result for same inputs • Functions are encapsulated • Interface / function name tells you about behaviour • Functions are commutative • Order doesn’t matter • Data is immutable • You have to create another copy to change object
  35. Patterns invisible in FP • Peter Norvig discussed how most

    of the GoF patterns are invisible or simpler in LISP
 http://www.norvig.com/design-patterns/ • Norvig says patterns “programming language bug reports” • Why OO Sucks by Joe Armstrong (Some bashing)
  36. Functional Principles • Data in, data out • Declarative style

    • Immutability • Prefer verbs instead of nouns • Strong typing (if possible in your lang) • No nulls (use libraries to use ‘Option’ like) • Lazy evaluation • Composition
  37. Data in, data out • Only purpose should be data

    in and data out. Should not do anything else. • Easily tastable
  38. 
 def add(a: Int, b: Int): Int = { return

    a + b }
 add(31, 11) It can be as simple like that
  39. Declarative Style • Say what are you doing, instead of

    how you are doing it. • Many small functions • E.g. one line collection processing with map, filter etc
  40. 
 def printArgs(args: Array[String]): Unit = { var i =

    0 while (i < args.length) { println(args(i)) i += 1 } }
  41. Immutability • Like Strings in Java or C# • ‘Effective

    Java’ & ‘Effective C#’ have sections on how to do it.
  42. Strong typing Goal is to find errors at compile time.


    
 type FirstName = String // type alias in Scala
 User(name: FirstName, email: EmailAddress)
 case class Customer(name: FirstName)

  43. Composition • Objects don’t compose easily • Objects that represent

    data structures with little behaviour usually do compose
 • Functions can be easily composed. • FP composition is mathematical notion of function composition
 f(g(x))
  44. val input = "Live as if you were to die

    tomorrow Learn as if you were to live forever" val grammerMap = Map("as" -> "adverb", "live" -> "verb", "if" -> "conjunction", "you" -> "pronoun", "were" -> "verb", "to" -> "preposition", "die" -> "verb", "tomorrow" -> "noun", "learn" -> "verb", "forever" -> "adverb") val highlight = (s: String) => { s.toUpperCase() } val grammarify = (word: String) => { val code = grammerMap(word.toLowerCase()) "<" + code + ">" + word + "<" + code + "/>" } val fComposeG = grammarify.compose(highlight) val partOfSpeechDetector = (str: String) => { str.split(" ").map(fComposeG).mkString(" ") } partOfSpeechDetector(input)
 <verb>LIVE<verb/> <adverb>AS<adverb/> <conjunction>IF<conjunction/> <pronoun>YOU<pronoun/> <verb>WERE<verb/> <preposition>TO<preposition/> <verb>DIE<verb/> <noun>TOMORROW<noun/> <verb>LEARN<verb/> <adverb>AS<adverb/> <conjunction>IF<conjunction/> <pronoun>YOU<pronoun/> <verb>WERE<verb/> <preposition>TO<preposition/> <verb>LIVE<verb/> <adverb>FOREVER<adverb/>
  45. 80s • Multi paradigm languages • Smalltalk 80 had lambda

    expressions • Common Lisp Object System • Polyglot programmers • Fertile language research • Implementation Progress - GC, JITs, etc.
  46. 90s and 2000s • 90s ruined everything • Huge Java

    popularity ramp • Servlets, J2EE then Spring • Virtual death of Smalltalk, LISP then Perl • Object Oriented Dominance
  47. Now • Increasingly multi paradigms languages are now dominating •

    Established languages are going multi paradigm • Java 8 - Generics + Lambdas • C++ Templates • Newer Languages are multi paradigm • F#, OCaml • Ruby / Python / Groovy • New JVM languages - Scala, Ceylon, Kotlin
  48. Go Functional • Write declarative code • Focus on what

    and not how • Avoid mutations, prefer immutability • Write more functions • Use functional composition λ
  49. References • http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ • http://blog.ploeh.dk/2012/05/25/Designpatternsacrossparadigms/ • Functional JavaScript - Michael

    Fogus • http://www.infoq.com/news/2014/03/oo-functional-programming • https://skillsmatter.com/skillscasts/5156-twins-fp-and-oop-1 • http://worrydream.com/refs/Hughes-WhyFunctionalProgrammingMatters.pdf • http://xahlee.info/comp/oop.html • http://gorodinski.com/blog/2013/09/18/oop-patterns-from-a-functional-perspective/ • http://harmful.cat-v.org/software/OO_programming/why_oo_sucks • http://www.defmacro.org/ramblings/fp.html • http://zeroturnaround.com/rebellabs/why-the-debate-on-object-oriented-vs-functional-programming- is-all-about-composition/ • Getting started Developing with Scala - Kelsey Gilmore - Innis & Jason Swartz