SlideShare una empresa de Scribd logo
1 de 44
Descargar para leer sin conexión
OOP and FP
Richard Warburton
If you feel like this, please give me feedback
What on earth are you talking about?
SOLID Principles
Anthropology
The other guy disgusts me
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
What on earth are you talking about?
SOLID Principles
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, if you’re mortally offended there are other talks you can go to.
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();
}

Factory 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++
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)
Extreme Structural Example
# let x =
object
val mutable x = 5
method get_x = x
method set_x y = x <- y
end;;
val x : < get_x : int; set_x : int -> unit >=<obj>
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
What on earth are you talking about?
SOLID Principles
Anthropology
The 1980s were great!
The 1990s ruined everything
Now everyone is friends
@richardwarburto
insightfullogic.com

Más contenido relacionado

La actualidad más candente

Scala the good and bad parts
Scala the good and bad partsScala the good and bad parts
Scala the good and bad parts
benewu
 
Top 10+ Things .NET Developers Should Know About Ruby
Top 10+ Things .NET Developers Should Know About RubyTop 10+ Things .NET Developers Should Know About Ruby
Top 10+ Things .NET Developers Should Know About Ruby
Jeff Cohen
 

La actualidad más candente (20)

JavaScript, qué hermoso eres
JavaScript, qué hermoso eresJavaScript, qué hermoso eres
JavaScript, qué hermoso eres
 
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
Advanced Object Oriented JavaScript (prototype, closure, scope, design patterns)
 
Groovy / comparison with java
Groovy / comparison with javaGroovy / comparison with java
Groovy / comparison with java
 
Exception Handling - Part 1
Exception Handling - Part 1 Exception Handling - Part 1
Exception Handling - Part 1
 
TDC2016SP - Groovy como você nunca viu
TDC2016SP - Groovy como você nunca viuTDC2016SP - Groovy como você nunca viu
TDC2016SP - Groovy como você nunca viu
 
Scala the good and bad parts
Scala the good and bad partsScala the good and bad parts
Scala the good and bad parts
 
Meta Programming in Groovy
Meta Programming in GroovyMeta Programming in Groovy
Meta Programming in Groovy
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Intro to java 8
Intro to java 8Intro to java 8
Intro to java 8
 
Ruby
RubyRuby
Ruby
 
Top 10+ Things .NET Developers Should Know About Ruby
Top 10+ Things .NET Developers Should Know About RubyTop 10+ Things .NET Developers Should Know About Ruby
Top 10+ Things .NET Developers Should Know About Ruby
 
XKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & ConstructsXKE - Programming Paradigms & Constructs
XKE - Programming Paradigms & Constructs
 
Scala - the good, the bad and the very ugly
Scala - the good, the bad and the very uglyScala - the good, the bad and the very ugly
Scala - the good, the bad and the very ugly
 
Android with kotlin course
Android with kotlin courseAndroid with kotlin course
Android with kotlin course
 
OCL in EMF
OCL in EMFOCL in EMF
OCL in EMF
 
Exploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App developmentExploring Kotlin language basics for Android App development
Exploring Kotlin language basics for Android App development
 
Contracts in Ruby - Vladyslav Hesal
Contracts in Ruby - Vladyslav HesalContracts in Ruby - Vladyslav Hesal
Contracts in Ruby - Vladyslav Hesal
 
Groovy AST Transformations
Groovy AST TransformationsGroovy AST Transformations
Groovy AST Transformations
 
Common Programming Paradigms
Common Programming ParadigmsCommon Programming Paradigms
Common Programming Paradigms
 
principles of object oriented class design
principles of object oriented class designprinciples of object oriented class design
principles of object oriented class design
 

Similar a Twins: OOP and FP

Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
BalamuruganV28
 
Object Oriented Programming_combined.ppt.pdf
Object Oriented Programming_combined.ppt.pdfObject Oriented Programming_combined.ppt.pdf
Object Oriented Programming_combined.ppt.pdf
AshutoshKumar211882
 

Similar a Twins: OOP and FP (20)

Twins: OOP and FP
Twins: OOP and FPTwins: OOP and FP
Twins: OOP and FP
 
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
 
TWINS: OOP and FP - Warburton
TWINS: OOP and FP - WarburtonTWINS: OOP and FP - Warburton
TWINS: OOP and FP - Warburton
 
Java - A broad introduction
Java - A broad introductionJava - A broad introduction
Java - A broad introduction
 
Design patterns in javascript
Design patterns in javascriptDesign patterns in javascript
Design patterns in javascript
 
OOP vs COP
OOP vs COPOOP vs COP
OOP vs COP
 
Ayush oops
Ayush oopsAyush oops
Ayush oops
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
PyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous ProgrammingPyCon Canada 2019 - Introduction to Asynchronous Programming
PyCon Canada 2019 - Introduction to Asynchronous Programming
 
Object Oriented Programming
Object Oriented ProgrammingObject Oriented Programming
Object Oriented Programming
 
Object Oriented Programming All Unit Notes
Object Oriented Programming All Unit NotesObject Oriented Programming All Unit Notes
Object Oriented Programming All Unit Notes
 
Software Craftmanship - Cours Polytech
Software Craftmanship - Cours PolytechSoftware Craftmanship - Cours Polytech
Software Craftmanship - Cours Polytech
 
Smalltalk, the dynamic language
Smalltalk, the dynamic languageSmalltalk, the dynamic language
Smalltalk, the dynamic language
 
Polyglot
PolyglotPolyglot
Polyglot
 
TDD in Python With Pytest
TDD in Python With PytestTDD in Python With Pytest
TDD in Python With Pytest
 
pythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptxpythontraining-201jn026043638.pptx
pythontraining-201jn026043638.pptx
 
Exciting JavaScript - Part I
Exciting JavaScript - Part IExciting JavaScript - Part I
Exciting JavaScript - Part I
 
Object Oriented Programming_combined.ppt.pdf
Object Oriented Programming_combined.ppt.pdfObject Oriented Programming_combined.ppt.pdf
Object Oriented Programming_combined.ppt.pdf
 
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
Functional Patterns for C++ Multithreading (C++ Dev Meetup Iasi)
 
Object Oriented Concepts and Principles
Object Oriented Concepts and PrinciplesObject Oriented Concepts and Principles
Object Oriented Concepts and Principles
 

Más de RichardWarburton

Más de RichardWarburton (20)

Fantastic performance and where to find it
Fantastic performance and where to find itFantastic performance and where to find it
Fantastic performance and where to find it
 
Production profiling what, why and how technical audience (3)
Production profiling  what, why and how   technical audience (3)Production profiling  what, why and how   technical audience (3)
Production profiling what, why and how technical audience (3)
 
Production profiling: What, Why and How
Production profiling: What, Why and HowProduction profiling: What, Why and How
Production profiling: What, Why and How
 
Production profiling what, why and how (JBCN Edition)
Production profiling  what, why and how (JBCN Edition)Production profiling  what, why and how (JBCN Edition)
Production profiling what, why and how (JBCN Edition)
 
Production Profiling: What, Why and How
Production Profiling: What, Why and HowProduction Profiling: What, Why and How
Production Profiling: What, Why and How
 
Java collections the force awakens
Java collections  the force awakensJava collections  the force awakens
Java collections the force awakens
 
Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)Generics Past, Present and Future (Latest)
Generics Past, Present and Future (Latest)
 
Collections forceawakens
Collections forceawakensCollections forceawakens
Collections forceawakens
 
Generics past, present and future
Generics  past, present and futureGenerics  past, present and future
Generics past, present and future
 
Jvm profiling under the hood
Jvm profiling under the hoodJvm profiling under the hood
Jvm profiling under the hood
 
How to run a hackday
How to run a hackdayHow to run a hackday
How to run a hackday
 
Generics Past, Present and Future
Generics Past, Present and FutureGenerics Past, Present and Future
Generics Past, Present and Future
 
Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)Pragmatic functional refactoring with java 8 (1)
Pragmatic functional refactoring with java 8 (1)
 
Performance and predictability (1)
Performance and predictability (1)Performance and predictability (1)
Performance and predictability (1)
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8Pragmatic functional refactoring with java 8
Pragmatic functional refactoring with java 8
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behave
 
Introduction to lambda behave
Introduction to lambda behaveIntroduction to lambda behave
Introduction to lambda behave
 
Performance and predictability
Performance and predictabilityPerformance and predictability
Performance and predictability
 
Simplifying java with lambdas (short)
Simplifying java with lambdas (short)Simplifying java with lambdas (short)
Simplifying java with lambdas (short)
 

Último

Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Último (20)

CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
AI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by AnitarajAI in Action: Real World Use Cases by Anitaraj
AI in Action: Real World Use Cases by Anitaraj
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
JohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptxJohnPollard-hybrid-app-RailsConf2024.pptx
JohnPollard-hybrid-app-RailsConf2024.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 

Twins: OOP and FP

  • 1. OOP and FP Richard Warburton
  • 2. If you feel like this, please give me feedback
  • 3. What on earth are you talking about? SOLID Principles Anthropology
  • 4. The other guy disgusts me
  • 5. 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
  • 6.
  • 7. What on earth are you talking about? SOLID Principles 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, if you’re mortally offended there are other talks you can go to.
  • 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(); } Factory 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++
  • 29. 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)
  • 30. Extreme Structural Example # let x = object val mutable x = 5 method get_x = x method set_x y = x <- y end;; val x : < get_x : int; set_x : int -> unit >=<obj>
  • 31. 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
  • 32. Thoughts on ISP ● Structural Subtyping obliviates the need for Interface Segregation Principle ● Functional Interfaces provide a nominalstructural bridge ● ISP != implementing 500 interfaces
  • 34. 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
  • 35. Streams Library album.getMusicians() .filter(artist -> artist.name().contains(“The”)) .map(artist -> artist.getNationality()) .collect(toList());
  • 36. 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); } }
  • 37. Business Logic private List<String> findHeadings() { return withLinesOf(file, lines -> lines.filter(isHeading) .collect(toList()), HeadingLookupException::new); }
  • 38. 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); } }
  • 39. DIP Summary ● Higher Order Functions also provide Inversion of Control ● Abstraction != interface ● Functional resource handling, eg withFile in haskell
  • 40. What on earth are you talking about? SOLID Principles Anthropology
  • 41. The 1980s were great!
  • 42. The 1990s ruined everything
  • 43. Now everyone is friends