Slide 1

Slide 1 text

Anil Wadghule
 @anildigital λ The Next Step is Functional February, 2015

Slide 2

Slide 2 text

• 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

Slide 3

Slide 3 text

• 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

Slide 4

Slide 4 text

Change is only CONSTANT Your application will change

Slide 5

Slide 5 text

• Rigid - Difficult to change • Fragile - Easily breakable • Immobile - Reuse is impossible • Viscous - Toughness in preserving design Smells of bad design

Slide 6

Slide 6 text

SOLID principles https://www.flickr.com/photos/fdecomite/2710132377

Slide 7

Slide 7 text

• Basic Object Oriented Programming principles
 • Makes programs easier to maintain & extend over time
 • Guidelines to remove code smells SOLID principles

Slide 8

Slide 8 text

Single Responsibility Open Closed Liskov’s Substitution Interface Segregation Dependency Inversion

Slide 9

Slide 9 text

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

Slide 10

Slide 10 text

• Software entities (classes, modules, methods) should be open for extension, but closed for modification Open Closed Principle

Slide 11

Slide 11 text

• Subtypes must be substitutable for their base types Liskov’s Substitution

Slide 12

Slide 12 text

• 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

Slide 13

Slide 13 text

• Depend on abstractions. Do not depend on concretions Dependency Inversion

Slide 14

Slide 14 text

Programming paradigms Imperative Procedural Object Oriented Functional Aspect Oriented Logic ? ? ? ? Symbolic

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

Objects are merely a poor mans’ closures.

Slide 18

Slide 18 text

A parable http://www.clipartpal.com/_thumbs/005/001/Business_Occupations/Religious/Monks/religion_buddhism_92898_tns.png

Slide 19

Slide 19 text

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

Slide 20

Slide 20 text

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

Slide 21

Slide 21 text

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

Slide 22

Slide 22 text

Closures are poor man’s object.

Slide 23

Slide 23 text

Single Responsibility → Smaller classes

Slide 24

Slide 24 text

Interface Segregation → Favour Role Interfaces over Header Interface

Slide 25

Slide 25 text

Lets see an example of such extreme object oriented code

Slide 26

Slide 26 text

http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 public interface IMessageQuery { string Read(int id); }

Slide 27

Slide 27 text

Objects as data with behaviour

Slide 28

Slide 28 text

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); } }


Slide 29

Slide 29 text

FileStore class is a simple example of data with behaviour • The behaviour is Read method • The data (also sometimes known as state) is workingDirectory

Slide 30

Slide 30 text

Functions as pure behaviour Closures wrap data

Slide 31

Slide 31 text

Before we see Closures, lets see Functions

Slide 32

Slide 32 text

C# Func

Slide 33

Slide 33 text

http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 Func read = (workingDirectory, id) => { var path = Path.Combine(workingDirectory.FullName, id + ".txt"); return File.ReadAllText(path); };

Slide 34

Slide 34 text

There is no data and you pass workingDirectory to it. 
 This doesn’t look like object. And is just a simple function.

Slide 35

Slide 35 text

Closures as behaviour with data

Slide 36

Slide 36 text

C# Closure

Slide 37

Slide 37 text

http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 var workingDirectory = new DirectoryInfo(Environment.CurrentDirectory);
 
 Func read = id => { var path = Path.Combine(workingDirectory.FullName, id + ".txt"); return File.ReadAllText(path); };

Slide 38

Slide 38 text

It’s closure, because function closes over the outer variable workingDirectory. 
 Effectively, the function captures the value of the outer variable.

Slide 39

Slide 39 text

What does that compile to?

Slide 40

Slide 40 text

http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 [CompilerGenerated] private sealed class <>c__DisplayClass3 { public DirectoryInfo workingDirectory; public string b__2(int id) { return File.ReadAllText( Path.Combine(this.workingDirectory.FullName, id + ".txt")); } }

Slide 41

Slide 41 text

Closures are behaviour with data Objects are data with behaviour whereas

Slide 42

Slide 42 text

Partial function application

Slide 43

Slide 43 text

http://blog.ploeh.dk/2014/03/10/solid-the-next-step-is-functional/ 
 Func read = (workingDirectory, id) => { var path = Path.Combine(workingDirectory.FullName, id + ".txt"); return File.ReadAllText(path); }; var wd = new DirectoryInfo(Environment.CurrentDirectory); Func r = id => read(wd, id); // Returns partial function r(42); r(99);


Slide 44

Slide 44 text

F# Closure

Slide 45

Slide 45 text

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)


Slide 46

Slide 46 text

Pure function and partial application

Slide 47

Slide 47 text

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)

Slide 48

Slide 48 text

Enlightenment https://secure.flickr.com/photos/h-k-d/3421452549/

Slide 49

Slide 49 text

Why Functional programming?

Slide 50

Slide 50 text

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

Slide 51

Slide 51 text

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()

Slide 52

Slide 52 text

Object Oriented Interaction ShowButton click() HiddenPanel show() InfoPanel show() display()

Slide 53

Slide 53 text

Object Oriented Style Too many objects, too many states, mutations and hence s

Slide 54

Slide 54 text

No content

Slide 55

Slide 55 text

Functional Style md toHTML modifyDOM postProcess Problem broken into Functional Parts

Slide 56

Slide 56 text

Functional Style md toHTML postProcess modifyDOM Functions are also composed together to form more behaviours. visit post addId genID composed of

Slide 57

Slide 57 text

Functional Style md toHTML postProcess modifyDOM text html decorated html

Slide 58

Slide 58 text

Functional Style A functional program is a machine for transforming data

Slide 59

Slide 59 text

Paper talks about how higher order functions and lazy evaluations contribute significantly to modularity

Slide 60

Slide 60 text

Why Functional programming? • Elegance • Purity • Avoid mistakes and easy debugging • Facilitates multithreaded programming / concurrency • Programming with values

Slide 61

Slide 61 text

• 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?

Slide 62

Slide 62 text

SOLID vs FP

Slide 63

Slide 63 text

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

Slide 64

Slide 64 text

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

Slide 65

Slide 65 text

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.

Slide 66

Slide 66 text

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

Slide 67

Slide 67 text

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

Slide 68

Slide 68 text

SOLID vs FP http://www.slideshare.net/ScottWlaschin/fp-patterns-buildstufflt

Slide 69

Slide 69 text

SOLID vs FP So what it boils down to. • Just use functions and higher order functions • SOLID Principles followed by default in FP

Slide 70

Slide 70 text

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

Slide 71

Slide 71 text

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)

Slide 72

Slide 72 text

Patterns invisible in FP

Slide 73

Slide 73 text

Patterns invisible in FP

Slide 74

Slide 74 text

Functional Principles for an 
 Object Oriented Programmer

Slide 75

Slide 75 text

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

Slide 76

Slide 76 text

Data in, data out • Only purpose should be data in and data out. Should not do anything else. • Easily tastable

Slide 77

Slide 77 text


 def add(a: Int, b: Int): Int = { return a + b }
 add(31, 11) It can be as simple like that

Slide 78

Slide 78 text

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

Slide 79

Slide 79 text


 def printArgs(args: Array[String]): Unit = { var i = 0 while (i < args.length) { println(args(i)) i += 1 } }

Slide 80

Slide 80 text


 def printArgs(args: Array[String]): Unit = { for (arg <- args) println(arg) }

Slide 81

Slide 81 text

Declarative Style 
 def printArgs(args: Array[String]): Unit = { args.foreach(println) }

Slide 82

Slide 82 text

Declarative Style 
 def formatArgs(args: Array[String]) = args.mkString("\n")

Slide 83

Slide 83 text

Immutability • The value of an identifier never changes. • Objects never change.

Slide 84

Slide 84 text

Immutability • Like Strings in Java or C# • ‘Effective Java’ & ‘Effective C#’ have sections on how to do it.

Slide 85

Slide 85 text

Immutability • Concurrency • Parallelism

Slide 86

Slide 86 text

Immutability In functional languages
 • Pure: Everything is immutable • Hybrid: Immutable by default

Slide 87

Slide 87 text

Prefer verbs to nouns In FP langs, functions are values. They can be passed just like data.

Slide 88

Slide 88 text

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)


Slide 89

Slide 89 text

No nulls Use Optional in Java 8 or using Guava

Slide 90

Slide 90 text

Lazy Evaluation Delay evaluation of an expression until the last responsible moment

Slide 91

Slide 91 text

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))

Slide 92

Slide 92 text

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)
 LIVE AS IF YOU WERE TO DIE TOMORROW LEARN AS IF YOU WERE TO LIVE FOREVER

Slide 93

Slide 93 text

80s, 90s, Now

Slide 94

Slide 94 text

80s • Multi paradigm languages • Smalltalk 80 had lambda expressions • Common Lisp Object System • Polyglot programmers • Fertile language research • Implementation Progress - GC, JITs, etc.

Slide 95

Slide 95 text

90s and 2000s • 90s ruined everything • Huge Java popularity ramp • Servlets, J2EE then Spring • Virtual death of Smalltalk, LISP then Perl • Object Oriented Dominance

Slide 96

Slide 96 text

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

Slide 97

Slide 97 text

Go Functional • Write declarative code • Focus on what and not how • Avoid mutations, prefer immutability • Write more functions • Use functional composition λ

Slide 98

Slide 98 text

Thank you @anildigital λ

Slide 99

Slide 99 text

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