SlideShare a Scribd company logo
1 of 75
Download to read offline
OOP and FP 
Richard Warburton
What on earth are you talking about? 
SOLID Principles 
Design Patterns 
Anthropology
In Quotes ... 
"OOP is to writing a program, what going through airport 
security is to flying" 
- Richard Mansfield 
"TDD replaces a type checker in Ruby in the same way that 
a strong drink replaces sorrows." 
- byorgey
In Quotes ... 
"Brain explosion is like a traditional pasttime in #haskell" 
"Some people claim everything is lisp. One time I was 
eating some spaghetti and someone came by and said: 
'Hey, nice lisp dialect you're hacking in there'"
Caveat: some unorthodox definitions may be 
provided
What on earth are you talking about? 
SOLID Principles 
Design Patterns 
Anthropology
SOLID Principles 
● Basic Object Oriented Programming 
Principles 
● Make programs easier to maintain 
● Guidelines to remove code smells
Single Responsibility Principle 
● Each class/method should have single 
responsibility 
● Responsibility means “reason to change” 
● The responsibility should be encapsulated
int countPrimes(int upTo) { 
int tally = 0; 
for (int i = 1; i < upTo; i++) { 
boolean isPrime = true; 
for (int j = 2; j < i; j++) { 
if (i % j == 0) { 
isPrime = false; 
} 
} 
if (isPrime) { 
tally++; 
} 
} 
return tally; 
}
int countPrimes(int upTo) { 
int tally = 0; 
for (int i = 1; i < upTo; i++) { 
if (isPrime(i)) { 
tally++; 
} 
} 
return tally; 
} 
boolean isPrime(int number) { 
for (int i = 2; i < number; i++) { 
if (number % i == 0) { 
return false; 
} 
} 
return true; 
}
long countPrimes(int upTo) { 
return IntStream.range(1, upTo) 
.filter(this::isPrime) 
.count(); 
} 
boolean isPrime(int number) { 
return IntStream.range(2, number) 
.allMatch(x -> (number % x) != 0); 
}
Higher Order Functions 
● Hard to write single responsibility code in 
Java before 8 
● Single responsibility requires ability to pass 
around behaviour 
● Not just functions, Higher Order Functions
Open Closed Principle
"software entities should be open for extension, 
but closed for modification" 
- Bertrand Meyer
Example: Graphing Metric Data
OCP as Polymorphism 
● Graphing Metric Data 
○ CpuUsage 
○ ProcessDiskWrite 
○ MachineIO 
● GraphDisplay depends upon a 
TimeSeries rather than each individually 
● No need to change GraphDisplay to add 
SwapTime
OCP as High Order Function 
// Example creation 
ThreadLocal<DateFormat> formatter = 
withInitial(() -> new SimpleDateFormat()); 
// Usage 
DateFormat formatter = formatter.get(); 
// Or ... 
AtomicInteger threadId = new AtomicInteger(); 
ThreadLocal<Integer> formatter = 
withInitial(() -> threadId.getAndIncrement());
OCP as Immutability 
● Immutable Object cannot be modified after 
creation 
● Safe to add additional behaviour 
● New pure functions can’t break existing 
functionality because it can’t change state
Liskov Substitution Principle 
Let q(x) be a property provable about objects 
x of type T. Then q(y) should be true for 
objects y of type S where S is a subtype of T. 
* Excuse the informality
A subclass behaves like its parent. 
* This is a conscious simplification
1. Where the parent worked the child should. 
2. Where the parent caused an effect then the 
child should. 
3. Where parent always stuck by something 
then the child should. 
4. Don’t change things your parent didn’t.
Functional Perspective 
● Inheritance isn’t key to FP 
● Lesson: don’t inherit implementation and 
LSP isn’t an issue! 
● Composite Reuse Principle already 
commonly accepted OOP principle
Interface Segregation Principle 
"The dependency of one class to another one 
should depend on the smallest possible 
interface" 
- Robert Martin
Factory Example 
interface Worker { 
public void goHome(); 
public void work(); 
} 
AssemblyLine requires instances of 
Worker: AssemblyWorker and Manager
The factories start using robots... 
… but a Robot doesn’t goHome()
Nominal Subtyping 
● For Foo to extend Bar you need to see Foo 
extends Bar in your code. 
● Relationship explicit between types based 
on the name of the type 
● Common in Statically Typed, OO languages: 
Java, C++
class AssemblyWorker implements 
Worker 
class Manager implements Worker 
class Robot implements Worker
public void addWorker(Worker worker) { 
workers.add(worker); 
} 
public static AssemblyLine newLine() { 
AssemblyLine line = new AssemblyLine(); 
line.addWorker(new Manager()); 
line.addWorker(new AssemblyWorker()); 
line.addWorker(new Robot()); 
return line; 
}
Structural Subtyping 
● Relationship implicit between types based 
on the shape/structure of the type 
● If you call obj.getFoo() then obj needs a 
getFoo method 
● Common in wacky language: Ocaml, Go, 
C++ Templates, Ruby (quack quack)
class StructuralWorker { 
def work(step:ProductionStep) { 
println( 
"I'm working on: " 
+ step.getName) 
} 
}
def addWorker(worker: {def work(step:ProductionStep)}) { 
workers += worker 
} 
def newLine() = { 
val line = new AssemblyLine 
line.addWorker(new Manager()) 
line.addWorker(new StructuralWorker()) 
line.addWorker(new Robot()) 
line 
}
Hypothetically … 
def addWorker(worker) { 
workers += worker 
} 
def newLine() = { 
val line = new AssemblyLine 
line.addWorker(new Manager()) 
line.addWorker(new StructuralWorker()) 
line.addWorker(new Robot()) 
line 
}
Functional Interfaces 
● An interface with a single abstract 
method 
● By definition the minimal interface! 
● Used as the inferred types for lambda 
expressions in Java 8
Thoughts on ISP 
● Structural Subtyping removes the need for 
Interface Segregation Principle 
● Functional Interfaces provide a nominal-structural 
bridge 
● ISP != implementing 500 interfaces
Dependency Inversion Principle
Dependency Inversion Principle 
● Abstractions should not depend on details, 
details should depend on abstractions 
● Decouple glue code from business logic 
● Inversion of Control/Dependency Injection is 
an implementation of DIP
Streams Library 
album.getMusicians() 
.filter(artist -> artist.name().contains(“The”)) 
.map(artist -> artist.getNationality()) 
.collect(toList());
Resource Handling & Logic 
List<String> findHeadings() { 
try (BufferedReader reader 
= new BufferedReader(new FileReader(file))) { 
return reader.lines() 
.filter(isHeading) 
.collect(toList()); 
} catch (IOException e) { 
throw new HeadingLookupException(e); 
} 
}
Business Logic 
private List<String> findHeadings() { 
return withLinesOf(file, 
lines -> lines.filter(isHeading) 
.collect(toList()), 
HeadingLookupException::new); 
}
Resource Handling 
<T> T withLinesOf(String file, 
Function<Stream<String>, T> handler, 
Function<IOException, 
RuntimeException> error) { 
try (BufferedReader reader = 
new BufferedReader(new FileReader(file))) { 
return handler.apply(reader.lines()); 
} catch (IOException e) { 
throw error.apply(e); 
} 
}
DIP Summary 
● Higher Order Functions also provide 
Inversion of Control 
● Abstraction != interface 
● Functional resource handling, eg withFile 
in haskell
All the solid patterns have a functional 
equivalent
The same idea expressed in different ways
What on earth are you talking about? 
SOLID Principles 
Design Patterns 
Anthropology
Command Pattern 
• Receiver - performs the actual work. 
• Command - encapsulates all the information 
required to call the receiver. 
• Invoker - controls the sequencing and 
execution of one or more commands. 
• Client - creates concrete command instances
Macro: take something that’s long and make it short
public interface Editor { 
public void save(); 
public void open(); 
public void close(); 
}
public interface Action { 
public void perform(); 
}
public class Open implements Action { 
private final Editor editor; 
public Open(Editor editor) { 
this.editor = editor; 
} 
public void perform() { 
editor.open(); 
} 
}
public class Macro { 
private final List<Action> actions; 
… 
public void record(Action action) { 
actions.add(action); 
} 
public void run() { 
actions.forEach(Action::perform); 
} 
}
Macro macro = new Macro(); 
macro.record(new Open(editor)); 
macro.record(new Save(editor)); 
macro.record(new Close(editor)); 
macro.run();
The Command Object is a Function 
Macro macro = new Macro(); 
macro.record(() -> editor.open()); 
macro.record(() -> editor.save()); 
macro.record(() -> editor.close()); 
macro.run();
Observer Pattern
Concrete Example: Profiler 
public interface ProfileListener { 
public void accept(Profile profile); 
}
private final List<ProfileListener> listeners; 
public void addListener(ProfileListener listener) { 
listeners.add(listener); 
} 
private void accept(Profile profile) { 
for (ProfileListener listener : listeners) { 
listener.accept(profile) 
} 
}
Previously you needed to write this EVERY 
time.
Consumer<T> === T → () 
ProfileListener === Profile → () 
ActionListener === Action → ()
public class Listeners<T> implements Consumer<T> { 
private final List<Consumer<T>> consumers; 
public Listeners<T> add(Consumer<T> consumer) { 
consumers.add(consumer); 
return this; 
} 
@Override 
public void accept(T value) { 
consumers.forEach(consumer -> consumer.accept(value)); 
}
public ProfileListener provide( 
FlatViewModel flatModel, 
TreeViewModel treeModel) { 
Listeners<Profile> listener = new 
Listeners<Profile>() 
.of(flatModel::accept) 
.of(treeModel::accept); 
return listener::accept; 
}
Existing Design Patterns don’t need to be 
thrown away.
Existing Design Patterns can be improved.
What on earth are you talking about? 
SOLID Principles 
Design Patterns 
Anthropology
Popular programming language evolution 
follows Arnie’s career.
The 1980s were great!
Programming 80s style 
● Strongly multiparadigm languages 
○ Smalltalk 80 had lambda expressions 
○ Common Lisp Object System 
● Polyglot Programmers 
● Fertile Language Research 
● Implementation Progress - GC, JITs, etc.
The 1990s ruined everything
90s and 2000s Market Convergence 
● Huge Java popularity ramp 
○ Javaone in 2001 - 28,000 attendees 
○ Servlets, J2EE then Spring 
● Virtual death of Smalltalk, LISP then Perl 
● Object Oriented Dominance
Now everyone is friends
Increasingly Multiparadigm 
● Established languages going multiparadigm 
○ Java 8 - Generics + Lambdas 
○ C++ - Templates, Lambdas 
● Newer Languages are multi paradigm 
○ F# 
○ Ruby/Python/Groovy can be functional 
○ New JVM languages: 
■ Scala 
■ Ceylon 
■ Kotlin
http://java8training.com 
http://is.gd/javalambdas 
@richardwarburto 
http://insightfullogic.com

More Related Content

What's hot

JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript ObjectsReem Alattas
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and UtilitiesPramod Kumar
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modelingCodemotion
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Vadim Dubs
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2Hariz Mustafa
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Trisha Gee
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 

What's hot (20)

Java generics final
Java generics finalJava generics final
Java generics final
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Lazy java
Lazy javaLazy java
Lazy java
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
Use of Apache Commons and Utilities
Use of Apache Commons and UtilitiesUse of Apache Commons and Utilities
Use of Apache Commons and Utilities
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
From object oriented to functional domain modeling
From object oriented to functional domain modelingFrom object oriented to functional domain modeling
From object oriented to functional domain modeling
 
Kotlin
KotlinKotlin
Kotlin
 
Java Generics
Java GenericsJava Generics
Java Generics
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 
Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.Javaz. Functional design in Java 8.
Javaz. Functional design in Java 8.
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)Refactoring to Java 8 (Devoxx BE)
Refactoring to Java 8 (Devoxx BE)
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 

Viewers also liked

Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)RichardWarburton
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)RichardWarburton
 
Jvm profiling under the hood
Jvm profiling under the hoodJvm profiling under the hood
Jvm profiling under the hoodRichardWarburton
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and FutureRichardWarburton
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictabilityRichardWarburton
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakensRichardWarburton
 

Viewers also liked (7)

Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)
 
Jvm profiling under the hood
Jvm profiling under the hoodJvm profiling under the hood
Jvm profiling under the hood
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and Future
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
 
How to run a hackday
How to run a hackdayHow to run a hackday
How to run a hackday
 

Similar to Twins: Object Oriented Programming and Functional Programming

TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonCodemotion
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Ovidiu Farauanu
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programmingNico Ludwig
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionKent Huang
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureJayaram Sankaranarayanan
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAdam Getchell
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015senejug
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python ProgrammingDozie Agbo
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++Manzoor ALam
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patternsOlivier Bacs
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLIDFoyzul Karim
 

Similar to Twins: Object Oriented Programming and Functional Programming (20)

TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
(3) cpp procedural programming
(3) cpp procedural programming(3) cpp procedural programming
(3) cpp procedural programming
 
Clean Code: Chapter 3 Function
Clean Code: Chapter 3 FunctionClean Code: Chapter 3 Function
Clean Code: Chapter 3 Function
 
Advance python
Advance pythonAdvance python
Advance python
 
Beyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software ArchitectureBeyond PITS, Functional Principles for Software Architecture
Beyond PITS, Functional Principles for Software Architecture
 
Functional programming
Functional programmingFunctional programming
Functional programming
 
An Overview Of Python With Functional Programming
An Overview Of Python With Functional ProgrammingAn Overview Of Python With Functional Programming
An Overview Of Python With Functional Programming
 
05. haskell streaming io
05. haskell streaming io05. haskell streaming io
05. haskell streaming io
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
SeneJug java_8_prez_122015
SeneJug java_8_prez_122015SeneJug java_8_prez_122015
SeneJug java_8_prez_122015
 
First Steps in Python Programming
First Steps in Python ProgrammingFirst Steps in Python Programming
First Steps in Python Programming
 
02 functions, variables, basic input and output of c++
02   functions, variables, basic input and output of c++02   functions, variables, basic input and output of c++
02 functions, variables, basic input and output of c++
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patterns
 
Workflow Foundation 4
Workflow Foundation 4Workflow Foundation 4
Workflow Foundation 4
 
Software design principles SOLID
Software design principles SOLIDSoftware design principles SOLID
Software design principles SOLID
 

More from RichardWarburton

Fantastic performance and where to find it
Fantastic performance and where to find itFantastic performance and where to find it
Fantastic performance and where to find itRichardWarburton
 
Production profiling what, why and how technical audience (3)
Production profiling  what, why and how   technical audience (3)Production profiling  what, why and how   technical audience (3)
Production profiling what, why and how technical audience (3)RichardWarburton
 
Production profiling: What, Why and How
Production profiling: What, Why and HowProduction profiling: What, Why and How
Production profiling: What, Why and HowRichardWarburton
 
Production profiling what, why and how (JBCN Edition)
Production profiling  what, why and how (JBCN Edition)Production profiling  what, why and how (JBCN Edition)
Production profiling what, why and how (JBCN Edition)RichardWarburton
 
Production Profiling: What, Why and How
Production Profiling: What, Why and HowProduction Profiling: What, Why and How
Production Profiling: What, Why and HowRichardWarburton
 
Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)RichardWarburton
 
Generics past, present and future
Generics  past, present and futureGenerics  past, present and future
Generics past, present and futureRichardWarburton
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behaveRichardWarburton
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behaveRichardWarburton
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictabilityRichardWarburton
 
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)Simplifying java with lambdas (short)
Simplifying java with lambdas (short)RichardWarburton
 
Lambdas myths-and-mistakes
Lambdas myths-and-mistakesLambdas myths-and-mistakes
Lambdas myths-and-mistakesRichardWarburton
 
Lambdas: Myths and Mistakes
Lambdas: Myths and MistakesLambdas: Myths and Mistakes
Lambdas: Myths and MistakesRichardWarburton
 

More from RichardWarburton (20)

Fantastic performance and where to find it
Fantastic performance and where to find itFantastic performance and where to find it
Fantastic performance and where to find it
 
Production profiling what, why and how technical audience (3)
Production profiling  what, why and how   technical audience (3)Production profiling  what, why and how   technical audience (3)
Production profiling what, why and how technical audience (3)
 
Production profiling: What, Why and How
Production profiling: What, Why and HowProduction profiling: What, Why and How
Production profiling: What, Why and How
 
Production profiling what, why and how (JBCN Edition)
Production profiling  what, why and how (JBCN Edition)Production profiling  what, why and how (JBCN Edition)
Production profiling what, why and how (JBCN Edition)
 
Production Profiling: What, Why and How
Production Profiling: What, Why and HowProduction Profiling: What, Why and How
Production Profiling: What, Why and How
 
Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 
Generics past, present and future
Generics  past, present and futureGenerics  past, present and future
Generics past, present and future
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behave
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behave
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
 
The Bleeding Edge
The Bleeding EdgeThe Bleeding Edge
The Bleeding Edge
 
Lambdas myths-and-mistakes
Lambdas myths-and-mistakesLambdas myths-and-mistakes
Lambdas myths-and-mistakes
 
Caching in
Caching inCaching in
Caching in
 
Lambdas: Myths and Mistakes
Lambdas: Myths and MistakesLambdas: Myths and Mistakes
Lambdas: Myths and Mistakes
 
Better than a coin toss
Better than a coin tossBetter than a coin toss
Better than a coin toss
 
Devoxx uk lambdas hackday
Devoxx uk lambdas hackdayDevoxx uk lambdas hackday
Devoxx uk lambdas hackday
 
How to run a hackday
How to run a hackdayHow to run a hackday
How to run a hackday
 

Recently uploaded

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Recently uploaded (20)

Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdfThe Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
The Role of Taxonomy and Ontology in Semantic Layers - Heather Hedden.pdf
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

Twins: Object Oriented Programming and Functional Programming

  • 1. OOP and FP Richard Warburton
  • 2. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 3.
  • 4. In Quotes ... "OOP is to writing a program, what going through airport security is to flying" - Richard Mansfield "TDD replaces a type checker in Ruby in the same way that a strong drink replaces sorrows." - byorgey
  • 5. In Quotes ... "Brain explosion is like a traditional pasttime in #haskell" "Some people claim everything is lisp. One time I was eating some spaghetti and someone came by and said: 'Hey, nice lisp dialect you're hacking in there'"
  • 6.
  • 7. Caveat: some unorthodox definitions may be provided
  • 8. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 9. SOLID Principles ● Basic Object Oriented Programming Principles ● Make programs easier to maintain ● Guidelines to remove code smells
  • 10. Single Responsibility Principle ● Each class/method should have single responsibility ● Responsibility means “reason to change” ● The responsibility should be encapsulated
  • 11. int countPrimes(int upTo) { int tally = 0; for (int i = 1; i < upTo; i++) { boolean isPrime = true; for (int j = 2; j < i; j++) { if (i % j == 0) { isPrime = false; } } if (isPrime) { tally++; } } return tally; }
  • 12.
  • 13. int countPrimes(int upTo) { int tally = 0; for (int i = 1; i < upTo; i++) { if (isPrime(i)) { tally++; } } return tally; } boolean isPrime(int number) { for (int i = 2; i < number; i++) { if (number % i == 0) { return false; } } return true; }
  • 14. long countPrimes(int upTo) { return IntStream.range(1, upTo) .filter(this::isPrime) .count(); } boolean isPrime(int number) { return IntStream.range(2, number) .allMatch(x -> (number % x) != 0); }
  • 15. Higher Order Functions ● Hard to write single responsibility code in Java before 8 ● Single responsibility requires ability to pass around behaviour ● Not just functions, Higher Order Functions
  • 17. "software entities should be open for extension, but closed for modification" - Bertrand Meyer
  • 19. OCP as Polymorphism ● Graphing Metric Data ○ CpuUsage ○ ProcessDiskWrite ○ MachineIO ● GraphDisplay depends upon a TimeSeries rather than each individually ● No need to change GraphDisplay to add SwapTime
  • 20. OCP as High Order Function // Example creation ThreadLocal<DateFormat> formatter = withInitial(() -> new SimpleDateFormat()); // Usage DateFormat formatter = formatter.get(); // Or ... AtomicInteger threadId = new AtomicInteger(); ThreadLocal<Integer> formatter = withInitial(() -> threadId.getAndIncrement());
  • 21. OCP as Immutability ● Immutable Object cannot be modified after creation ● Safe to add additional behaviour ● New pure functions can’t break existing functionality because it can’t change state
  • 22. Liskov Substitution Principle Let q(x) be a property provable about objects x of type T. Then q(y) should be true for objects y of type S where S is a subtype of T. * Excuse the informality
  • 23.
  • 24. A subclass behaves like its parent. * This is a conscious simplification
  • 25. 1. Where the parent worked the child should. 2. Where the parent caused an effect then the child should. 3. Where parent always stuck by something then the child should. 4. Don’t change things your parent didn’t.
  • 26. Functional Perspective ● Inheritance isn’t key to FP ● Lesson: don’t inherit implementation and LSP isn’t an issue! ● Composite Reuse Principle already commonly accepted OOP principle
  • 27. Interface Segregation Principle "The dependency of one class to another one should depend on the smallest possible interface" - Robert Martin
  • 28. Factory Example interface Worker { public void goHome(); public void work(); } AssemblyLine requires instances of Worker: AssemblyWorker and Manager
  • 29. The factories start using robots... … but a Robot doesn’t goHome()
  • 30. Nominal Subtyping ● For Foo to extend Bar you need to see Foo extends Bar in your code. ● Relationship explicit between types based on the name of the type ● Common in Statically Typed, OO languages: Java, C++
  • 31. class AssemblyWorker implements Worker class Manager implements Worker class Robot implements Worker
  • 32. public void addWorker(Worker worker) { workers.add(worker); } public static AssemblyLine newLine() { AssemblyLine line = new AssemblyLine(); line.addWorker(new Manager()); line.addWorker(new AssemblyWorker()); line.addWorker(new Robot()); return line; }
  • 33. Structural Subtyping ● Relationship implicit between types based on the shape/structure of the type ● If you call obj.getFoo() then obj needs a getFoo method ● Common in wacky language: Ocaml, Go, C++ Templates, Ruby (quack quack)
  • 34. class StructuralWorker { def work(step:ProductionStep) { println( "I'm working on: " + step.getName) } }
  • 35. def addWorker(worker: {def work(step:ProductionStep)}) { workers += worker } def newLine() = { val line = new AssemblyLine line.addWorker(new Manager()) line.addWorker(new StructuralWorker()) line.addWorker(new Robot()) line }
  • 36. Hypothetically … def addWorker(worker) { workers += worker } def newLine() = { val line = new AssemblyLine line.addWorker(new Manager()) line.addWorker(new StructuralWorker()) line.addWorker(new Robot()) line }
  • 37. Functional Interfaces ● An interface with a single abstract method ● By definition the minimal interface! ● Used as the inferred types for lambda expressions in Java 8
  • 38. Thoughts on ISP ● Structural Subtyping removes the need for Interface Segregation Principle ● Functional Interfaces provide a nominal-structural bridge ● ISP != implementing 500 interfaces
  • 40. Dependency Inversion Principle ● Abstractions should not depend on details, details should depend on abstractions ● Decouple glue code from business logic ● Inversion of Control/Dependency Injection is an implementation of DIP
  • 41. Streams Library album.getMusicians() .filter(artist -> artist.name().contains(“The”)) .map(artist -> artist.getNationality()) .collect(toList());
  • 42. Resource Handling & Logic List<String> findHeadings() { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { return reader.lines() .filter(isHeading) .collect(toList()); } catch (IOException e) { throw new HeadingLookupException(e); } }
  • 43. Business Logic private List<String> findHeadings() { return withLinesOf(file, lines -> lines.filter(isHeading) .collect(toList()), HeadingLookupException::new); }
  • 44. Resource Handling <T> T withLinesOf(String file, Function<Stream<String>, T> handler, Function<IOException, RuntimeException> error) { try (BufferedReader reader = new BufferedReader(new FileReader(file))) { return handler.apply(reader.lines()); } catch (IOException e) { throw error.apply(e); } }
  • 45. DIP Summary ● Higher Order Functions also provide Inversion of Control ● Abstraction != interface ● Functional resource handling, eg withFile in haskell
  • 46. All the solid patterns have a functional equivalent
  • 47. The same idea expressed in different ways
  • 48. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 49. Command Pattern • Receiver - performs the actual work. • Command - encapsulates all the information required to call the receiver. • Invoker - controls the sequencing and execution of one or more commands. • Client - creates concrete command instances
  • 50. Macro: take something that’s long and make it short
  • 51. public interface Editor { public void save(); public void open(); public void close(); }
  • 52. public interface Action { public void perform(); }
  • 53. public class Open implements Action { private final Editor editor; public Open(Editor editor) { this.editor = editor; } public void perform() { editor.open(); } }
  • 54. public class Macro { private final List<Action> actions; … public void record(Action action) { actions.add(action); } public void run() { actions.forEach(Action::perform); } }
  • 55. Macro macro = new Macro(); macro.record(new Open(editor)); macro.record(new Save(editor)); macro.record(new Close(editor)); macro.run();
  • 56. The Command Object is a Function Macro macro = new Macro(); macro.record(() -> editor.open()); macro.record(() -> editor.save()); macro.record(() -> editor.close()); macro.run();
  • 58.
  • 59. Concrete Example: Profiler public interface ProfileListener { public void accept(Profile profile); }
  • 60. private final List<ProfileListener> listeners; public void addListener(ProfileListener listener) { listeners.add(listener); } private void accept(Profile profile) { for (ProfileListener listener : listeners) { listener.accept(profile) } }
  • 61. Previously you needed to write this EVERY time.
  • 62. Consumer<T> === T → () ProfileListener === Profile → () ActionListener === Action → ()
  • 63. public class Listeners<T> implements Consumer<T> { private final List<Consumer<T>> consumers; public Listeners<T> add(Consumer<T> consumer) { consumers.add(consumer); return this; } @Override public void accept(T value) { consumers.forEach(consumer -> consumer.accept(value)); }
  • 64. public ProfileListener provide( FlatViewModel flatModel, TreeViewModel treeModel) { Listeners<Profile> listener = new Listeners<Profile>() .of(flatModel::accept) .of(treeModel::accept); return listener::accept; }
  • 65. Existing Design Patterns don’t need to be thrown away.
  • 66. Existing Design Patterns can be improved.
  • 67. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 68. Popular programming language evolution follows Arnie’s career.
  • 69. The 1980s were great!
  • 70. Programming 80s style ● Strongly multiparadigm languages ○ Smalltalk 80 had lambda expressions ○ Common Lisp Object System ● Polyglot Programmers ● Fertile Language Research ● Implementation Progress - GC, JITs, etc.
  • 71. The 1990s ruined everything
  • 72. 90s and 2000s Market Convergence ● Huge Java popularity ramp ○ Javaone in 2001 - 28,000 attendees ○ Servlets, J2EE then Spring ● Virtual death of Smalltalk, LISP then Perl ● Object Oriented Dominance
  • 73. Now everyone is friends
  • 74. Increasingly Multiparadigm ● Established languages going multiparadigm ○ Java 8 - Generics + Lambdas ○ C++ - Templates, Lambdas ● Newer Languages are multi paradigm ○ F# ○ Ruby/Python/Groovy can be functional ○ New JVM languages: ■ Scala ■ Ceylon ■ Kotlin