SlideShare une entreprise Scribd logo
1  sur  47
A well-typed program never goes wrong julien@kaching.com Silicon Valley Code Camp 2010
µ-Java Imagine Java deprived of  all native types and  all control-flow constructs
Encoding ℕ in µ-Java A number is either zero or the successor of another number
Encoding ℕ in µ-Java interface Number { } class Zero implements Number { } class Successor implements Number { privatefinal Number predecessor;    Successor(Number predecessor) { this.predecessor = predecessor;     } }
Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one);
Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one); Number three = one.plus(two);
Encoding ℕ in µ-Java interface Number {     Number plus(Number that); }
Encoding ℕ in µ-Java class Zero implements Number {  public Number plus(Number that) {    } }
Encoding ℕ in µ-Java class Zero implements Number {  public Number plus(Number that) { return that;    } }
Encoding ℕ in µ-Java classSuccessor implementsNumber {  privatefinal Number predecessor;     Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) {    } }
Encoding ℕ in µ-Java classSuccessor implementsNumber {  privatefinal Number predecessor;     Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) { returnnew Successor(predecessor.plus(that));    } }
Encoding ℕ in µ-Java Base case:     0 + n = n Recurrence:     m + n = ((m - 1) + n) + 1
Growing a Language µ-Java expressiveness
Today’s Agenda Practical discussion of Type Safety. Grow your language to make it safer.
“I’ve written well-typed programs before,    and they went wrong!”
This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int
This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int scala> divide(4, 0) java.lang.ArithmeticException: / by zero at .divide(<console>:5)
Was it well-typed?
Was it well-typed? Yes, but the types didn’t fully convey the complexity of the domain. The type checker doesn’t know you can’t divide by 0 unless it is expressed by the types. How can you grow the language to address this issue?
Division by zero, revisited scala> abstractclass Number(n: Int) scala> caseclass Zero extends Number(0) scala> caseclassNonZero(n: Int) extends Number(n) scala> def number(n: Int) = if (n == 0) Zero elseNonZero(n)
Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero)
Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero) error: type mismatch;  found     : Zero  required: NonZero
Type Safety The extent to which a programming language discourages or prevents type errors. A type error is erroneous program behavior caused by a discrepancy between differing data types.
Well-typed programs never go wrong Preservation  Well typednessof programs remains invariant under the transition rules of the language.  Progress  A well typed program never gets into a state where no further transitions are possible.
Value Types Represents possibly infinite set of similarly kinded data transcending an application's life. Life cycles are meaningless. Value types are immutable. Usually restrict the universe of their underlying types.
Value Types classEmailAddressextends Value<String> { … classPrice extends Value<Long> { … class Id<E extends Entity> extends Value<Long> { …
The 1:1 Principle booleanplaceLimitOrder(Action, Integer, String, Long); booleanplaceLimitOrder(Action, Quantity, Ticker, Price);
Type Safe Bit Field Apple's ticker AAPL. What about Berkshire Hathaway’s?  Google says BRKA, Yahoo! BRK-A, Bloomberg BRK/A and  Reuters BRKa.
Type Safe Bit Field interfaceSecurityTag {   interfaceGoogle extendsSecurityTag{}   interfaceYahoo extendsSecurityTag{}   interfaceBloomberg extendsSecurityTag{}   interfaceReuters extendsSecurityTag{} }
Type Safe Bit Field classTaggedTicker<T extendsSecurityTag>  extends Value<String> { ...
Type Safe Bit Field Price getPriceFromGoogle( TaggedTicker<Google> ticker) { ...   voidsendBuyOrderToBloomberg( TaggedTicker<Bloomberg> ticker, Quantity quantity) { ..
Type Safe Bit Field interface Security {     <T extendsSecurityTag> TaggedTicker<T> getTaggedTicker(Class<T> kind); }
Type Safe Bit Field Map<Class<? extendsSecurityTag>, Long> TAG2MASK =   ImmutableMap.        <Class<? extendsSecurityTag>, Long> builder()             .put(SecurityTag.Google.class, 0x01)             .put(SecurityTag.Yahoo.class, 0x02)             .put(SecurityTag.Bloomberg.class, 0x04)             .put(SecurityTag.Reuters.class, 0x08)             .build();
Type Safe Bit Field <T extendsSecurityTag> void set(Class<T> kind) {   tags = (tags | TAG2MASK.get(kind)); } <T extendsSecurityTag> void unset(Class<T> kind) {   tags = (tags & ~TAG2MASK.get(kind)); }
Invariant Map A bunch of methods in java.util.Map are contravariant on the key type. This makes refactorings extremely error prone. java.util.Map#get(Object) java.util.Map#remove(Object) java.util.Map#containsKey (Object)
Invariant Map voiddoSomething(Map<Ticker, Quote> cache) {    … cache.remove(ticker);
Invariant Map voiddoSomething(Map<Isin, Quote> cache) {       … cache.remove(ticker);
Invariant Map interfaceInvariantMap<K, V> {    V get(K key);   V remove(K key);   ...
Invariant Map classInvariantMaps{ static<K, V> InvariantMap<K, V> newHashMap() { returndelegate(newHashMap<K, V>());   } static<K extends Comparable<? super K>, V>  InvariantMap<K, V> newTreeMap() { returndelegate(newTreeMap<K, V>());   }     …
Option abstractclass Option[T] caseclass None extends Option[Nothing] caseclass Some(x: T) extends Option[T] getUser(id) match { case Some(user) ⇒ … case None ⇒ … }
Option Much more verbose in Java... getUser(id).visit(newOptionVisitor<Unit>() { public Unit caseSome(User user) {         … publicUnit caseNone() {         … })
Option … but still useful! interfaceUserRepository {     Option<User> getUser(Id<User> id); User getUserOrThrow(Id<User> id); }
Abstracting the Control Flow We saw how to grow a language by introducing more types. We can also improve control flow structuresby abstracting the control flow.
Abstracting the Control Flow BigDecimal total = ZERO; for (BigDecimal value : values) { if (value.compareTo(ZERO) > 0) { total.add(value);    } } return total;
Abstracting the Control Flow returnsum(filter(        values,  new Predicate<BigDecimal>() { publicboolean apply(BigDecimal t) { return t.compareTo(ZERO) > 0;              }         }));
Abstracting the Control Flow Easier to re-use operations. The “wiring” between operations is checked by the type system.
References Foundations for Programming Languages John C. Mitchell I Can Has Invariant Mapz? http://eng.kaching.com/2010/07/i-can-has-invariant-mapz.html Type Safe Bit Fields Using Higher-KindedPolymorphism        http://eng.kaching.com/2010/08/type-safe-bit-fields-using-higher.html

Contenu connexe

Tendances

Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
singhadarsh
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
Ted Leung
 
Lecture 5 Inheritance
Lecture 5 InheritanceLecture 5 Inheritance
Lecture 5 Inheritance
bunnykhan
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
hmanjarawala
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Raga Vahini
 

Tendances (17)

Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Unit I Advanced Java Programming Course
Unit I   Advanced Java Programming CourseUnit I   Advanced Java Programming Course
Unit I Advanced Java Programming Course
 
Generics and collections in Java
Generics and collections in JavaGenerics and collections in Java
Generics and collections in Java
 
Lecture 1
Lecture 1Lecture 1
Lecture 1
 
Chapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class InheritanceChapter 7:Understanding Class Inheritance
Chapter 7:Understanding Class Inheritance
 
Ch6
Ch6Ch6
Ch6
 
Chapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic ConceptsChapter 4:Object-Oriented Basic Concepts
Chapter 4:Object-Oriented Basic Concepts
 
Being Expressive in Code
Being Expressive in CodeBeing Expressive in Code
Being Expressive in Code
 
Basic elements of java
Basic elements of java Basic elements of java
Basic elements of java
 
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJSeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
 
Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Dynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner TypingDynamic Type Inference for Gradual Hindley–Milner Typing
Dynamic Type Inference for Gradual Hindley–Milner Typing
 
Lecture 5 Inheritance
Lecture 5 InheritanceLecture 5 Inheritance
Lecture 5 Inheritance
 
Intake 37 6
Intake 37 6Intake 37 6
Intake 37 6
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Ppt of c vs c#
Ppt of c vs c#Ppt of c vs c#
Ppt of c vs c#
 

Similaire à A well-typed program never goes wrong

Tim Popl
Tim PoplTim Popl
Tim Popl
mchaar
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
Jussi Pohjolainen
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
parag978978
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
webuploader
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
Sachin Singh
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
Satish Verma
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
Garth Gilmour
 

Similaire à A well-typed program never goes wrong (20)

C tutorial
C tutorialC tutorial
C tutorial
 
C C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.inC C++ tutorial for beginners- tibacademy.in
C C++ tutorial for beginners- tibacademy.in
 
The Next Mainstream Programming Language: A Game Developer’s Perspective
The Next Mainstream Programming Language: A Game Developer’s PerspectiveThe Next Mainstream Programming Language: A Game Developer’s Perspective
The Next Mainstream Programming Language: A Game Developer’s Perspective
 
Tim Popl
Tim PoplTim Popl
Tim Popl
 
C#
C#C#
C#
 
Rits Brown Bag - TypeScript
Rits Brown Bag - TypeScriptRits Brown Bag - TypeScript
Rits Brown Bag - TypeScript
 
Programming with Java: the Basics
Programming with Java: the BasicsProgramming with Java: the Basics
Programming with Java: the Basics
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5Paradigmas de Linguagens de Programacao - Aula #5
Paradigmas de Linguagens de Programacao - Aula #5
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
core java
 core java core java
core java
 
Introduction to typescript
Introduction to typescriptIntroduction to typescript
Introduction to typescript
 
javasebeyondbasics
javasebeyondbasicsjavasebeyondbasics
javasebeyondbasics
 
Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1Introduction to-csharp-1229579367461426-1
Introduction to-csharp-1229579367461426-1
 
Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
A Sceptical Guide to Functional Programming
A Sceptical Guide to Functional ProgrammingA Sceptical Guide to Functional Programming
A Sceptical Guide to Functional Programming
 
Dart programming language
Dart programming languageDart programming language
Dart programming language
 
unit 1 (1).pptx
unit 1 (1).pptxunit 1 (1).pptx
unit 1 (1).pptx
 
JavaScript Foundations Day1
JavaScript Foundations Day1JavaScript Foundations Day1
JavaScript Foundations Day1
 

Dernier

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
"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 ...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
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
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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
 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
 
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu SubbuApidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
Apidays Singapore 2024 - Modernizing Securities Finance by Madhu Subbu
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
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
 
A Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source MilvusA Beginners Guide to Building a RAG App Using Open Source Milvus
A Beginners Guide to Building a RAG App Using Open Source Milvus
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 

A well-typed program never goes wrong

  • 1. A well-typed program never goes wrong julien@kaching.com Silicon Valley Code Camp 2010
  • 2. µ-Java Imagine Java deprived of all native types and all control-flow constructs
  • 3. Encoding ℕ in µ-Java A number is either zero or the successor of another number
  • 4. Encoding ℕ in µ-Java interface Number { } class Zero implements Number { } class Successor implements Number { privatefinal Number predecessor; Successor(Number predecessor) { this.predecessor = predecessor; } }
  • 5. Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one);
  • 6. Encoding ℕ in µ-Java Number zero = new Zero(); Number one = new Successor(zero); Number two = new Successor(one); Number three = one.plus(two);
  • 7. Encoding ℕ in µ-Java interface Number { Number plus(Number that); }
  • 8. Encoding ℕ in µ-Java class Zero implements Number { public Number plus(Number that) { } }
  • 9. Encoding ℕ in µ-Java class Zero implements Number { public Number plus(Number that) { return that; } }
  • 10. Encoding ℕ in µ-Java classSuccessor implementsNumber { privatefinal Number predecessor; Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) { } }
  • 11. Encoding ℕ in µ-Java classSuccessor implementsNumber { privatefinal Number predecessor; Successor(Number predecessor) { this.predecessor = predecessor; } public Number plus(Number that) { returnnew Successor(predecessor.plus(that)); } }
  • 12. Encoding ℕ in µ-Java Base case: 0 + n = n Recurrence: m + n = ((m - 1) + n) + 1
  • 13. Growing a Language µ-Java expressiveness
  • 14. Today’s Agenda Practical discussion of Type Safety. Grow your language to make it safer.
  • 15. “I’ve written well-typed programs before, and they went wrong!”
  • 16. This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int
  • 17. This will definitely go wrong scala> defdivide(a: Int, b: Int) = a / b divide: (a: Int,b: Int)Int scala> divide(4, 0) java.lang.ArithmeticException: / by zero at .divide(<console>:5)
  • 19. Was it well-typed? Yes, but the types didn’t fully convey the complexity of the domain. The type checker doesn’t know you can’t divide by 0 unless it is expressed by the types. How can you grow the language to address this issue?
  • 20. Division by zero, revisited scala> abstractclass Number(n: Int) scala> caseclass Zero extends Number(0) scala> caseclassNonZero(n: Int) extends Number(n) scala> def number(n: Int) = if (n == 0) Zero elseNonZero(n)
  • 21. Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero)
  • 22. Division by zero, revisited scala> abstractclass Number(n: Int) { def divide(that: NonZero) = number(n / that.n) } scala> number(4).divide(Zero) error: type mismatch; found : Zero required: NonZero
  • 23. Type Safety The extent to which a programming language discourages or prevents type errors. A type error is erroneous program behavior caused by a discrepancy between differing data types.
  • 24. Well-typed programs never go wrong Preservation Well typednessof programs remains invariant under the transition rules of the language. Progress A well typed program never gets into a state where no further transitions are possible.
  • 25. Value Types Represents possibly infinite set of similarly kinded data transcending an application's life. Life cycles are meaningless. Value types are immutable. Usually restrict the universe of their underlying types.
  • 26. Value Types classEmailAddressextends Value<String> { … classPrice extends Value<Long> { … class Id<E extends Entity> extends Value<Long> { …
  • 27. The 1:1 Principle booleanplaceLimitOrder(Action, Integer, String, Long); booleanplaceLimitOrder(Action, Quantity, Ticker, Price);
  • 28. Type Safe Bit Field Apple's ticker AAPL. What about Berkshire Hathaway’s? Google says BRKA, Yahoo! BRK-A, Bloomberg BRK/A and Reuters BRKa.
  • 29. Type Safe Bit Field interfaceSecurityTag {   interfaceGoogle extendsSecurityTag{}   interfaceYahoo extendsSecurityTag{}   interfaceBloomberg extendsSecurityTag{}   interfaceReuters extendsSecurityTag{} }
  • 30. Type Safe Bit Field classTaggedTicker<T extendsSecurityTag> extends Value<String> { ...
  • 31. Type Safe Bit Field Price getPriceFromGoogle( TaggedTicker<Google> ticker) { ...   voidsendBuyOrderToBloomberg( TaggedTicker<Bloomberg> ticker, Quantity quantity) { ..
  • 32. Type Safe Bit Field interface Security { <T extendsSecurityTag> TaggedTicker<T> getTaggedTicker(Class<T> kind); }
  • 33. Type Safe Bit Field Map<Class<? extendsSecurityTag>, Long> TAG2MASK = ImmutableMap. <Class<? extendsSecurityTag>, Long> builder()      .put(SecurityTag.Google.class, 0x01)      .put(SecurityTag.Yahoo.class, 0x02)      .put(SecurityTag.Bloomberg.class, 0x04)      .put(SecurityTag.Reuters.class, 0x08)      .build();
  • 34. Type Safe Bit Field <T extendsSecurityTag> void set(Class<T> kind) { tags = (tags | TAG2MASK.get(kind)); } <T extendsSecurityTag> void unset(Class<T> kind) { tags = (tags & ~TAG2MASK.get(kind)); }
  • 35. Invariant Map A bunch of methods in java.util.Map are contravariant on the key type. This makes refactorings extremely error prone. java.util.Map#get(Object) java.util.Map#remove(Object) java.util.Map#containsKey (Object)
  • 36. Invariant Map voiddoSomething(Map<Ticker, Quote> cache) { … cache.remove(ticker);
  • 37. Invariant Map voiddoSomething(Map<Isin, Quote> cache) { … cache.remove(ticker);
  • 38. Invariant Map interfaceInvariantMap<K, V> { V get(K key); V remove(K key); ...
  • 39. Invariant Map classInvariantMaps{ static<K, V> InvariantMap<K, V> newHashMap() { returndelegate(newHashMap<K, V>()); } static<K extends Comparable<? super K>, V> InvariantMap<K, V> newTreeMap() { returndelegate(newTreeMap<K, V>()); } …
  • 40. Option abstractclass Option[T] caseclass None extends Option[Nothing] caseclass Some(x: T) extends Option[T] getUser(id) match { case Some(user) ⇒ … case None ⇒ … }
  • 41. Option Much more verbose in Java... getUser(id).visit(newOptionVisitor<Unit>() { public Unit caseSome(User user) { … publicUnit caseNone() { … })
  • 42. Option … but still useful! interfaceUserRepository { Option<User> getUser(Id<User> id); User getUserOrThrow(Id<User> id); }
  • 43. Abstracting the Control Flow We saw how to grow a language by introducing more types. We can also improve control flow structuresby abstracting the control flow.
  • 44. Abstracting the Control Flow BigDecimal total = ZERO; for (BigDecimal value : values) { if (value.compareTo(ZERO) > 0) { total.add(value); } } return total;
  • 45. Abstracting the Control Flow returnsum(filter( values, new Predicate<BigDecimal>() { publicboolean apply(BigDecimal t) { return t.compareTo(ZERO) > 0; } }));
  • 46. Abstracting the Control Flow Easier to re-use operations. The “wiring” between operations is checked by the type system.
  • 47. References Foundations for Programming Languages John C. Mitchell I Can Has Invariant Mapz? http://eng.kaching.com/2010/07/i-can-has-invariant-mapz.html Type Safe Bit Fields Using Higher-KindedPolymorphism http://eng.kaching.com/2010/08/type-safe-bit-fields-using-higher.html