SlideShare a Scribd company logo
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

More Related Content

What's hot

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
 

What's hot (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
 

Similar to 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
 

Similar to 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
 

More from 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
 

More from 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
 

Recently uploaded

To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsPaul Groth
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlPeter Udo Diehl
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform EngineeringJemma Hussein Allen
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...Elena Simperl
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)Ralf Eggert
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Alison B. Lowndes
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...Product School
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»QADay
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Product School
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyJohn Staveley
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...Sri Ambati
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Product School
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxAbida Shariff
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀DianaGray10
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Thierry Lestable
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsExpeed Software
 

Recently uploaded (20)

To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo DiehlFuture Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
Future Visions: Predictions to Guide and Time Tech Innovation, Peter Udo Diehl
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...When stars align: studies in data quality, knowledge graphs, and machine lear...
When stars align: studies in data quality, knowledge graphs, and machine lear...
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»НАДІЯ ФЕДЮШКО БАЦ  «Професійне зростання QA спеціаліста»
НАДІЯ ФЕДЮШКО БАЦ «Професійне зростання QA спеціаліста»
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
Demystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John StaveleyDemystifying gRPC in .Net by John Staveley
Demystifying gRPC in .Net by John Staveley
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
Exploring UiPath Orchestrator API: updates and limits in 2024 🚀
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualitySoftware Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered Quality
 
In-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT ProfessionalsIn-Depth Performance Testing Guide for IT Professionals
In-Depth Performance Testing Guide for IT Professionals
 

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