SlideShare une entreprise Scribd logo
1  sur  75
Télécharger pour lire hors ligne
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
// 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 High Order Function
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
● 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
Dependency Inversion Principle
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://is.gd/javalambdas
@richardwarburto
http://insightfullogic.com
Q & A

Contenu connexe

Tendances

Functional solid
Functional solidFunctional solid
Functional solidMatt Stine
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code DevelopmentPeter Gfader
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpen Gurukul
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design PatternsStefano Fago
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEUehara Junji
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answerssheibansari
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Uehara Junji
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Juan Pablo
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - GenericsRoshan Deniyage
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code SmellsMario Sangiorgio
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2Hariz Mustafa
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)HamletDRC
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScriptNascenia IT
 

Tendances (20)

Functional solid
Functional solidFunctional solid
Functional solid
 
Clean Code Development
Clean Code DevelopmentClean Code Development
Clean Code Development
 
OpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ ProgrammingOpenGurukul : Language : C++ Programming
OpenGurukul : Language : C++ Programming
 
C# 6.0 Preview
C# 6.0 PreviewC# 6.0 Preview
C# 6.0 Preview
 
C++ references
C++ referencesC++ references
C++ references
 
Uncommon Design Patterns
Uncommon Design PatternsUncommon Design Patterns
Uncommon Design Patterns
 
Migrating to JUnit 5
Migrating to JUnit 5Migrating to JUnit 5
Migrating to JUnit 5
 
C++ aptitude
C++ aptitudeC++ aptitude
C++ aptitude
 
Easy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVEEasy Going Groovy 2nd season on DevLOVE
Easy Going Groovy 2nd season on DevLOVE
 
C++aptitude questions and answers
C++aptitude questions and answersC++aptitude questions and answers
C++aptitude questions and answers
 
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
Let's go Developer 2011 sendai Let's go Java Developer (Programming Language ...
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Javascript
JavascriptJavascript
Javascript
 
Java Programming - 03 java control flow
Java Programming - 03 java control flowJava Programming - 03 java control flow
Java Programming - 03 java control flow
 
Effective Java - Generics
Effective Java - GenericsEffective Java - Generics
Effective Java - Generics
 
Clean code
Clean codeClean code
Clean code
 
Clean code and Code Smells
Clean code and Code SmellsClean code and Code Smells
Clean code and Code Smells
 
Lecture02 class -_templatev2
Lecture02 class -_templatev2Lecture02 class -_templatev2
Lecture02 class -_templatev2
 
Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)Groovy Ast Transformations (greach)
Groovy Ast Transformations (greach)
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 

Similaire à TWINS: OOP and FP - Warburton

From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()daewon jeong
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol Efe
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy CodeRowan Merewood
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVAMuskanSony
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest UpdatesIftekhar Eather
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeIan Robertson
 
20100730 phpstudy
20100730 phpstudy20100730 phpstudy
20100730 phpstudyYusuke Ando
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Hammad Rajjoub
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patternsOlivier Bacs
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworksMD Sayem Ahmed
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Guillaume Laforge
 

Similaire à TWINS: OOP and FP - Warburton (20)

From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Scala is java8.next()
Scala is java8.next()Scala is java8.next()
Scala is java8.next()
 
Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
S emb t13-freertos
S emb t13-freertosS emb t13-freertos
S emb t13-freertos
 
More about PHP
More about PHPMore about PHP
More about PHP
 
SOLID
SOLIDSOLID
SOLID
 
Living With Legacy Code
Living With Legacy CodeLiving With Legacy Code
Living With Legacy Code
 
Gwt.create
Gwt.createGwt.create
Gwt.create
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
Introducing PHP Latest Updates
Introducing PHP Latest UpdatesIntroducing PHP Latest Updates
Introducing PHP Latest Updates
 
Lambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive CodeLambda Chops - Recipes for Simpler, More Expressive Code
Lambda Chops - Recipes for Simpler, More Expressive Code
 
20100730 phpstudy
20100730 phpstudy20100730 phpstudy
20100730 phpstudy
 
Combating software entropy 2-roc1-
Combating software entropy 2-roc1-Combating software entropy 2-roc1-
Combating software entropy 2-roc1-
 
Reviewing OOP Design patterns
Reviewing OOP Design patternsReviewing OOP Design patterns
Reviewing OOP Design patterns
 
Ontopia tutorial
Ontopia tutorialOntopia tutorial
Ontopia tutorial
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
A brief overview of java frameworks
A brief overview of java frameworksA brief overview of java frameworks
A brief overview of java frameworks
 
Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008Groovy Introduction - JAX Germany - 2008
Groovy Introduction - JAX Germany - 2008
 

Plus de Codemotion

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Codemotion
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyCodemotion
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaCodemotion
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserCodemotion
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Codemotion
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Codemotion
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Codemotion
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 - Codemotion
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Codemotion
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Codemotion
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Codemotion
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Codemotion
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Codemotion
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Codemotion
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Codemotion
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...Codemotion
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Codemotion
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Codemotion
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Codemotion
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Codemotion
 

Plus de Codemotion (20)

Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
Fuzz-testing: A hacker's approach to making your code more secure | Pascal Ze...
 
Pompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending storyPompili - From hero to_zero: The FatalNoise neverending story
Pompili - From hero to_zero: The FatalNoise neverending story
 
Pastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storiaPastore - Commodore 65 - La storia
Pastore - Commodore 65 - La storia
 
Pennisi - Essere Richard Altwasser
Pennisi - Essere Richard AltwasserPennisi - Essere Richard Altwasser
Pennisi - Essere Richard Altwasser
 
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
Michel Schudel - Let's build a blockchain... in 40 minutes! - Codemotion Amst...
 
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
Richard Süselbeck - Building your own ride share app - Codemotion Amsterdam 2019
 
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
Eward Driehuis - What we learned from 20.000 attacks - Codemotion Amsterdam 2019
 
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 - Francesco Baldassarri  - Deliver Data at Scale - Codemotion Amsterdam 2019 -
Francesco Baldassarri - Deliver Data at Scale - Codemotion Amsterdam 2019 -
 
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
Martin Förtsch, Thomas Endres - Stereoscopic Style Transfer AI - Codemotion A...
 
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
Melanie Rieback, Klaus Kursawe - Blockchain Security: Melting the "Silver Bul...
 
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
Angelo van der Sijpt - How well do you know your network stack? - Codemotion ...
 
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
Lars Wolff - Performance Testing for DevOps in the Cloud - Codemotion Amsterd...
 
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
Sascha Wolter - Conversational AI Demystified - Codemotion Amsterdam 2019
 
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
Michele Tonutti - Scaling is caring - Codemotion Amsterdam 2019
 
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
Pat Hermens - From 100 to 1,000+ deployments a day - Codemotion Amsterdam 2019
 
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
James Birnie - Using Many Worlds of Compute Power with Quantum - Codemotion A...
 
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
Don Goodman-Wilson - Chinese food, motor scooters, and open source developmen...
 
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
Pieter Omvlee - The story behind Sketch - Codemotion Amsterdam 2019
 
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
Dave Farley - Taking Back “Software Engineering” - Codemotion Amsterdam 2019
 
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
Joshua Hoffman - Should the CTO be Coding? - Codemotion Amsterdam 2019
 

Dernier

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
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
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 

Dernier (20)

Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
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
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
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
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 

TWINS: OOP and FP - Warburton

  • 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. // 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 High Order Function
  • 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. ● 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 Dependency Inversion Principle
  • 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