SlideShare una empresa de Scribd logo
1 de 74
Descargar para leer sin conexión
OOP and FP
Richard Warburton
What on earth are you talking about?
SOLID Principles
Design Patterns
Anthropology
In Quotes ...
"I find OOP technically unsound”
- Alexander Stepanov
OOP prevents any one programmer from "doing too much damage."
- Paul Graham
"OOP is to writing a program, what going through airport security is to flying"
- Richard Mansfield
"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'"
"TDD replaces a type checker in Ruby in the same way that a strong drink
replaces sorrows."
- byorgey
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, M&S higher order
functions
Open Closed Principle
"software entities should be open for extension,
but closed for modification"
- Bertrand Meyer
OCP as Polymorphism
● Graphing Metric Data
○ CpuUsage
○ ProcessDiskWrite
○ MachineIO

● GraphDisplay depends upon a
TimeSeries rather than each individually
● No need to change GraphDisplay to add
SwapTime
OCP by Functions as Arguments
// Example creation
ThreadLocal<DateFormat> formatter =
withInitial(() -> new SimpleDateFormat());
// Usage
DateFormat formatter = formatter.get();
// Or ...
AtomicInteger threadId = new AtomicInteger();
ThreadLocal<Integer> formatter =
withInitial(() -> threadId.getAndIncrement());
OCP as Immutability
● Immutable Object cannot be modified after
creation
● Safe to add additional behaviour
● New pure functions can’t break existing
functionality because it can’t change state
Liskov Substitution Principle

Let q(x) be a property provable about objects
x of type T. Then q(y) should be true for
objects y of type S where S is a subtype of T.

* Excuse the informality
A subclass behaves like its parent.

* This is a conscious simplification
1. Where the parent worked the child should.
2. Where the parent caused an effect then the
child should.
3. Where parent always stuck by something
then the child should.
4. Don’t change things your parent didn’t.
Functional Perspective
● Inheritance isn’t key to FP
● Lesson: don’t inherit implementation and
LSP isn’t an issue!
● Composite Reuse Principle already
commonly accepted OOP principle
Interface Segregation Principle

"The dependency of one class to another one
should depend on the smallest possible
interface"
- Robert Martin
Factory Example
interface Worker {
public void goHome();
public void work();
}

AssemblyLine requires instances of
Worker: AssemblyWorker and Manager
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
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 obliviates the need for
Interface Segregation Principle
● Functional Interfaces provide a nominalstructural bridge
● ISP != implementing 500 interfaces
Dependency Inversion Principle
Dependency Inversion Principle
● Abstractions should not depend on details,
details should depend on abstractions
● Decouple glue code from business logic
● Inversion of Control/Dependency Injection is
an implementation of DIP
Streams Library

album.getMusicians()
.filter(artist -> artist.name().contains(“The”))
.map(artist -> artist.getNationality())
.collect(toList());
Resource Handling & Logic
List<String> findHeadings() {
try (BufferedReader reader
= new BufferedReader(new FileReader(file))) {
return reader.lines()
.filter(isHeading)
.collect(toList());
} catch (IOException e) {
throw new HeadingLookupException(e);
}
}
Business Logic

private List<String> findHeadings() {
return withLinesOf(file,
lines -> lines.filter(isHeading)
.collect(toList()),
HeadingLookupException::new);
}
Resource Handling
<T> T withLinesOf(String file,
Function<Stream<String>, T> handler,
Function<IOException,
RuntimeException> error) {
try (BufferedReader reader =
new BufferedReader(new FileReader(file))) {
return handler.apply(reader.lines());
} catch (IOException e) {
throw error.apply(e);
}
}
DIP Summary
● Higher Order Functions also provide
Inversion of Control
● Abstraction != interface
● Functional resource handling, eg withFile
in haskell
All the solid patterns have a functional
equivalent
The same idea expressed in different ways
What on earth are you talking about?
SOLID Principles
Design Patterns
Anthropology
Command Pattern
• Receiver - performs the actual work.
• Command - encapsulates all the information
required to call the receiver.
• Invoker - controls the sequencing and
execution of one or more commands.
• Client - creates concrete command instances
Macro: take something that’s long and make it short
public interface Editor {
public void save();
public void open();
public void close();
}
public interface Action {
public void perform();
}
public class Open implements Action {
private final Editor editor;
public Open(Editor editor) {
this.editor = editor;
}
public void perform() {
editor.open();
}
}
public class Macro {
private final List<Action> actions;
…
public void record(Action action) {
actions.add(action);
}
public void run() {
actions.forEach(Action::perform);
}
}
Macro macro = new Macro();
macro.record(new Open(editor));
macro.record(new Save(editor));
macro.record(new Close(editor));
macro.run();
The Command Object is a Function
Macro macro = new Macro();
macro.record(editor::open);
macro.record(editor::save);
macro.record(editor::close);
macro.run();
Observer Pattern
Concrete Example: Profiler
public interface ProfileListener {
public void accept(Profile profile);
}
private final List<ProfileListener> listeners;
public void addListener(ProfileListener listener) {
listeners.add(listener);
}
private void accept(Profile profile) {
for (ProfileListener listener : listeners) {
listener.accept(profile)
}
}
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
Q&A

http://is.gd/javalambdas
@richardwarburto
http://insightfullogic.com

Más contenido relacionado

La actualidad más candente

Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtimeInferis
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overviewFantageek
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptForziatech
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engineDuoyi Wu
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderAndres Almiray
 
Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Yulia Tsisyk
 
Sonar rules in action with walkmod
Sonar rules in action with walkmodSonar rules in action with walkmod
Sonar rules in action with walkmodRaquel Pau
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptecker
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for ProgrammersDavid Rodenas
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesAnkit Rastogi
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac pluginOleksandr Radchykov
 
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistakeFuture Processing
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetHDR1001
 
Qt test framework
Qt test frameworkQt test framework
Qt test frameworkICS
 
Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Andrea Francia
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtestWill Shen
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011Nicholas Zakas
 

La actualidad más candente (20)

Objective c runtime
Objective c runtimeObjective c runtime
Objective c runtime
 
Objective-C Runtime overview
Objective-C Runtime overviewObjective-C Runtime overview
Objective-C Runtime overview
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
Virtual machine and javascript engine
Virtual machine and javascript engineVirtual machine and javascript engine
Virtual machine and javascript engine
 
Svcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilderSvcc Building Rich Applications with Groovy's SwingBuilder
Svcc Building Rich Applications with Groovy's SwingBuilder
 
Svcc Groovy Testing
Svcc Groovy TestingSvcc Groovy Testing
Svcc Groovy Testing
 
Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"Adam Sitnik "State of the .NET Performance"
Adam Sitnik "State of the .NET Performance"
 
Sonar rules in action with walkmod
Sonar rules in action with walkmodSonar rules in action with walkmod
Sonar rules in action with walkmod
 
Introduzione al TDD
Introduzione al TDDIntroduzione al TDD
Introduzione al TDD
 
Advanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScriptAdvanced Object-Oriented JavaScript
Advanced Object-Oriented JavaScript
 
ReactJS for Programmers
ReactJS for ProgrammersReactJS for Programmers
ReactJS for Programmers
 
Ten useful JavaScript tips & best practices
Ten useful JavaScript tips & best practicesTen useful JavaScript tips & best practices
Ten useful JavaScript tips & best practices
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Code generation with javac plugin
Code generation with javac pluginCode generation with javac plugin
Code generation with javac plugin
 
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake
[Quality Meetup] Piotr Wittchen - Fixing a billion dollar mistake
 
JavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat SheetJavaScript Object Oriented Programming Cheat Sheet
JavaScript Object Oriented Programming Cheat Sheet
 
Qt test framework
Qt test frameworkQt test framework
Qt test framework
 
Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008Google C++ Testing Framework in Visual Studio 2008
Google C++ Testing Framework in Visual Studio 2008
 
20111018 boost and gtest
20111018 boost and gtest20111018 boost and gtest
20111018 boost and gtest
 
Maintainable JavaScript 2011
Maintainable JavaScript 2011Maintainable JavaScript 2011
Maintainable JavaScript 2011
 

Destacado

Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictabilityRichardWarburton
 
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)Simplifying java with lambdas (short)
Simplifying java with lambdas (short)RichardWarburton
 
Generics past, present and future
Generics  past, present and futureGenerics  past, present and future
Generics past, present and futureRichardWarburton
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behaveRichardWarburton
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behaveRichardWarburton
 
Jvm profiling under the hood
Jvm profiling under the hoodJvm profiling under the hood
Jvm profiling under the hoodRichardWarburton
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)RichardWarburton
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8RichardWarburton
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)RichardWarburton
 
Lambdas myths-and-mistakes
Lambdas myths-and-mistakesLambdas myths-and-mistakes
Lambdas myths-and-mistakesRichardWarburton
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and FutureRichardWarburton
 
Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)RichardWarburton
 

Destacado (15)

Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
 
Generics past, present and future
Generics  past, present and futureGenerics  past, present and future
Generics past, present and future
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behave
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behave
 
The Bleeding Edge
The Bleeding EdgeThe Bleeding Edge
The Bleeding Edge
 
Jvm profiling under the hood
Jvm profiling under the hoodJvm profiling under the hood
Jvm profiling under the hood
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)
 
Lambdas myths-and-mistakes
Lambdas myths-and-mistakesLambdas myths-and-mistakes
Lambdas myths-and-mistakes
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and Future
 
Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)
 

Similar a Twins: OOP and FP

2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2Leonid Maslov
 
A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9Marcus Lagergren
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part IEugene Lazutkin
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?Doug Hawkins
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascriptAyush Sharma
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleThierry Wasylczenko
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)Piyush Katariya
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot NetNeeraj Kaushik
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksMongoDB
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)xMartin12
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsRan Mizrahi
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introductionBirol Efe
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overviewjessesanford
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsAzul Systems, Inc.
 
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using AutomataModeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using AutomataDaniel Bristot de Oliveira
 

Similar a Twins: OOP and FP (20)

Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
JavaScript for real men
JavaScript for real menJavaScript for real men
JavaScript for real men
 
2. Design patterns. part #2
2. Design patterns. part #22. Design patterns. part #2
2. Design patterns. part #2
 
A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9A new execution model for Nashorn in Java 9
A new execution model for Nashorn in Java 9
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?JVM Mechanics: When Does the JVM JIT & Deoptimize?
JVM Mechanics: When Does the JVM JIT & Deoptimize?
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
Construire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradleConstruire une application JavaFX 8 avec gradle
Construire une application JavaFX 8 avec gradle
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
JavaScript (without DOM)
JavaScript (without DOM)JavaScript (without DOM)
JavaScript (without DOM)
 
Parallel Programming With Dot Net
Parallel Programming With Dot NetParallel Programming With Dot Net
Parallel Programming With Dot Net
 
Fun Teaching MongoDB New Tricks
Fun Teaching MongoDB New TricksFun Teaching MongoDB New Tricks
Fun Teaching MongoDB New Tricks
 
Gwt.create
Gwt.createGwt.create
Gwt.create
 
Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)Asynchronous Module Definition (AMD)
Asynchronous Module Definition (AMD)
 
[2015/2016] JavaScript
[2015/2016] JavaScript[2015/2016] JavaScript
[2015/2016] JavaScript
 
How AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design PatternsHow AngularJS Embraced Traditional Design Patterns
How AngularJS Embraced Traditional Design Patterns
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Dragoncraft Architectural Overview
Dragoncraft Architectural OverviewDragoncraft Architectural Overview
Dragoncraft Architectural Overview
 
Silicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM MechanicsSilicon Valley JUG: JVM Mechanics
Silicon Valley JUG: JVM Mechanics
 
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using AutomataModeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
Modeling the Behavior of Threads in the PREEMPT_RT Linux Kernel Using Automata
 

Más de RichardWarburton

Fantastic performance and where to find it
Fantastic performance and where to find itFantastic performance and where to find it
Fantastic performance and where to find itRichardWarburton
 
Production profiling what, why and how technical audience (3)
Production profiling  what, why and how   technical audience (3)Production profiling  what, why and how   technical audience (3)
Production profiling what, why and how technical audience (3)RichardWarburton
 
Production profiling: What, Why and How
Production profiling: What, Why and HowProduction profiling: What, Why and How
Production profiling: What, Why and HowRichardWarburton
 
Production profiling what, why and how (JBCN Edition)
Production profiling  what, why and how (JBCN Edition)Production profiling  what, why and how (JBCN Edition)
Production profiling what, why and how (JBCN Edition)RichardWarburton
 
Production Profiling: What, Why and How
Production Profiling: What, Why and HowProduction Profiling: What, Why and How
Production Profiling: What, Why and HowRichardWarburton
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakensRichardWarburton
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictabilityRichardWarburton
 
Lambdas: Myths and Mistakes
Lambdas: Myths and MistakesLambdas: Myths and Mistakes
Lambdas: Myths and MistakesRichardWarburton
 
Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)RichardWarburton
 

Más de RichardWarburton (14)

Fantastic performance and where to find it
Fantastic performance and where to find itFantastic performance and where to find it
Fantastic performance and where to find it
 
Production profiling what, why and how technical audience (3)
Production profiling  what, why and how   technical audience (3)Production profiling  what, why and how   technical audience (3)
Production profiling what, why and how technical audience (3)
 
Production profiling: What, Why and How
Production profiling: What, Why and HowProduction profiling: What, Why and How
Production profiling: What, Why and How
 
Production profiling what, why and how (JBCN Edition)
Production profiling  what, why and how (JBCN Edition)Production profiling  what, why and how (JBCN Edition)
Production profiling what, why and how (JBCN Edition)
 
Production Profiling: What, Why and How
Production Profiling: What, Why and HowProduction Profiling: What, Why and How
Production Profiling: What, Why and How
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
 
How to run a hackday
How to run a hackdayHow to run a hackday
How to run a hackday
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Caching in
Caching inCaching in
Caching in
 
Lambdas: Myths and Mistakes
Lambdas: Myths and MistakesLambdas: Myths and Mistakes
Lambdas: Myths and Mistakes
 
Better than a coin toss
Better than a coin tossBetter than a coin toss
Better than a coin toss
 
Devoxx uk lambdas hackday
Devoxx uk lambdas hackdayDevoxx uk lambdas hackday
Devoxx uk lambdas hackday
 
How to run a hackday
How to run a hackdayHow to run a hackday
How to run a hackday
 
Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)Caching in (DevoxxUK 2013)
Caching in (DevoxxUK 2013)
 

Último

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embeddingZilliz
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfSeasiaInfotech2
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 

Último (20)

AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Training state-of-the-art general text embedding
Training state-of-the-art general text embeddingTraining state-of-the-art general text embedding
Training state-of-the-art general text embedding
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
The Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdfThe Future of Software Development - Devin AI Innovative Approach.pdf
The Future of Software Development - Devin AI Innovative Approach.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 

Twins: OOP and FP

  • 1. OOP and FP Richard Warburton
  • 2. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 3.
  • 4. In Quotes ... "I find OOP technically unsound” - Alexander Stepanov OOP prevents any one programmer from "doing too much damage." - Paul Graham "OOP is to writing a program, what going through airport security is to flying" - Richard Mansfield "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'" "TDD replaces a type checker in Ruby in the same way that a strong drink replaces sorrows." - byorgey
  • 5.
  • 6. Caveat: some unorthodox definitions may be provided
  • 7. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 8. SOLID Principles ● Basic Object Oriented Programming Principles ● Make programs easier to maintain ● Guidelines to remove code smells
  • 9. Single Responsibility Principle ● Each class/method should have single responsibility ● Responsibility means “reason to change” ● The responsibility should be encapsulated
  • 10. 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; }
  • 11. 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; }
  • 12.
  • 13. 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); }
  • 14. Higher Order Functions ● Hard to write single responsibility code in Java before 8 ● Single responsibility requires ability to pass around behaviour ● Not just functions, M&S higher order functions
  • 16. "software entities should be open for extension, but closed for modification" - Bertrand Meyer
  • 17. 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
  • 18. OCP by Functions as Arguments // Example creation ThreadLocal<DateFormat> formatter = withInitial(() -> new SimpleDateFormat()); // Usage DateFormat formatter = formatter.get(); // Or ... AtomicInteger threadId = new AtomicInteger(); ThreadLocal<Integer> formatter = withInitial(() -> threadId.getAndIncrement());
  • 19. 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
  • 20. 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
  • 21.
  • 22. A subclass behaves like its parent. * This is a conscious simplification
  • 23. 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.
  • 24. 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
  • 25. Interface Segregation Principle "The dependency of one class to another one should depend on the smallest possible interface" - Robert Martin
  • 26. Factory Example interface Worker { public void goHome(); public void work(); } AssemblyLine requires instances of Worker: AssemblyWorker and Manager but a Robot doesn’t goHome()
  • 27. 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++
  • 28. class AssemblyWorker implements Worker class Manager implements Worker class Robot implements Worker
  • 29. 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; }
  • 31. 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)
  • 32. class StructuralWorker { def work(step:ProductionStep) { println( "I'm working on: " + step.getName) } }
  • 33. 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 }
  • 34. 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 }
  • 35. 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
  • 36. Thoughts on ISP ● Structural Subtyping obliviates the need for Interface Segregation Principle ● Functional Interfaces provide a nominalstructural bridge ● ISP != implementing 500 interfaces
  • 38. 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
  • 39. Streams Library album.getMusicians() .filter(artist -> artist.name().contains(“The”)) .map(artist -> artist.getNationality()) .collect(toList());
  • 40. 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); } }
  • 41. Business Logic private List<String> findHeadings() { return withLinesOf(file, lines -> lines.filter(isHeading) .collect(toList()), HeadingLookupException::new); }
  • 42. 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); } }
  • 43. DIP Summary ● Higher Order Functions also provide Inversion of Control ● Abstraction != interface ● Functional resource handling, eg withFile in haskell
  • 44. All the solid patterns have a functional equivalent
  • 45. The same idea expressed in different ways
  • 46. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 47. 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
  • 48. Macro: take something that’s long and make it short
  • 49. public interface Editor { public void save(); public void open(); public void close(); }
  • 50. public interface Action { public void perform(); }
  • 51. public class Open implements Action { private final Editor editor; public Open(Editor editor) { this.editor = editor; } public void perform() { editor.open(); } }
  • 52. public class Macro { private final List<Action> actions; … public void record(Action action) { actions.add(action); } public void run() { actions.forEach(Action::perform); } }
  • 53. Macro macro = new Macro(); macro.record(new Open(editor)); macro.record(new Save(editor)); macro.record(new Close(editor)); macro.run();
  • 54. The Command Object is a Function Macro macro = new Macro(); macro.record(editor::open); macro.record(editor::save); macro.record(editor::close); macro.run();
  • 56.
  • 57. Concrete Example: Profiler public interface ProfileListener { public void accept(Profile profile); }
  • 58. 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) } }
  • 60. Consumer<T> === () → T ProfileListener === () → Profile ActionListener === () → Action
  • 61. 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)); }
  • 62. public ProfileListener provide( FlatViewModel flatModel, TreeViewModel treeModel) { Listeners<Profile> listener = new Listeners<Profile>() .of(flatModel::accept) .of(treeModel::accept); return listener::accept; }
  • 63. Existing Design Patterns don’t need to be thrown away.
  • 64. Existing Design Patterns can be improved.
  • 65. What on earth are you talking about? SOLID Principles Design Patterns Anthropology
  • 66. Popular programming language evolution follows Arnie’s career.
  • 67. The 1980s were great!
  • 68. 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.
  • 69. The 1990s ruined everything
  • 70. 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
  • 71. Now everyone is friends
  • 72. 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
  • 73.