SlideShare a Scribd company logo
Expression Problem
Giuseppe Scopelliti
Platform Engineer | @peppescopellit1
Agenda
➢ Introduction
➢ Set up a use case
➢ Proposed solution
➢ Talk about pros and cons
➢ Q/A
Introduction 1/2
The expression problem is one in which the challenge
is:
➢ Define a data type with cases.
➢ Add new cases of the type, and operations for the
types.
➢ Avoid recompiling.
Introduction 2/2
Any implementation of the expression problem should
satisfy the following requirements:
➢ Extensibility in both dimensions.
➢ Strong static type safety.
➢ No modification of the existing code.
➢ Separate compilation.
Use case 1/3
We are using a third party library
case class Employee(name: String, id : Long)
trait Payroll {
def processEmployees(employees: Vector[Employee]): Either[String, Throwable]
}
Use case 2/3
We can easily add new types
class USPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]) = Left("US payroll")
}
class JapanPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]) = Left("Japan payroll")
}
Use case 3/3
What if we need to add new operations on the types?
E.g. Deal with Contractors
trait ExtendedPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]): Either[String, Throwable]
def processContractors(contractors: Vector[Contractor]): Either[String, Throwable]
}
In summary
OP
TYPE
This is a practical problem
How to add features to an
existing system
incrementally without
doing modifications?
Proposed solution
➔ Leverage scala traits and abstract type members to
solve the expression problem.
➔ Rewrite the same payroll system, so you can easily
add new operations to it, without breaking type-
safety, and at the same time add a new type.
Some Code 1/5The new payroll system will be:
trait PayrollSystem {
case class Employee(name: String, id: Long)
type P <: Payroll
trait Payroll {
def processEmployees(employees: Vector[Employee]): Either[String, Throwable]
}
def processPayroll(p: P): Either[String, Throwable]
}
// You nest everything inside a trait so that you can treat it as a module.
// The type P denotes some subtype of the Payroll trait,
// which declares an abstract method to process salaries for employees.
// The processPayroll method needs to be implemented to process payrolls for a
// given Payroll type.
Some Code 2/5We can still easily add a new type
trait USPayrollSystem extends PayrollSystem {
class USPayroll extends Payroll {
def processEmployees(employees: Vector[Employee]) = {
println("US payroll")
Left("US payroll")
}
}
}
PayrollSystem
USPayrollSystem
Some Code 3/5What about a new operation ?
trait ContractorPayrollSystem extends PayrollSystem {
case class Contractor(name: String)
//Shadowing the Payroll trait defined in PayrollSystem
trait Payroll extends super.Payroll {
def processContractors(contractors: Vector[Contractor]): Either[String,
Throwable]
}
}
PayrollSystem
USPayrollSystem
ContractorPayrollSystem
Some Code 4/5And ...
trait USContractorPayrollSystem extends USPayrollSystem with ContractorPayrollSystem
{
//We are shadowing the former definition of USPayroll.
class USPayroll extends super.USPayroll with Payroll {
def processContractors(contractors: Vector[Contractor]) = {
println("US contract payroll")
Left("US contract payroll")
}
}
}
PayrollSystem
USPayrollSystem
ContractorPayrollSystem
USContractorPayrollSystem
Some Code 5/5Finally ...
object USEmployeeAndContractorPayroll extends USContractorPayrollSystem {
type P = USPayroll
def processPayroll(p: USPayroll): Either[String, Throwable] = {
p.processEmployees(Vector(Employee("a", 1)))
p.processContractors(Vector(Contractor("b")))
Left("payroll processed successfully")
}
}
Proposed solution
This was a good example to demonstrate:
– The power of Scala’s type system
– The abstraction available to build scalable and
extensible components
We achieved a solution
OP
TYPE
Pros And Cons
– Inside the context, shadowing let you extend the old
definition, without overriding it.
– Shadowing can introduce unintended errors in your
code.
Thanks for listening!
Any Questions?
Some resources to get more details
❖ http://www.scala-lang.org/docu/files/TheExpressionProblem.pdf
❖ https://news.ycombinator.com/item?id=11683379
❖ http://fileadmin.cs.lth.se/sde/people/gorel/misc/ExpProblemTalkPart1.
pdf
❖ http://lambda-the-ultimate.org/node/3141
❖ https://prezi.com/wwqo9dtgqhs2/comparing-solutions-to-the-
expression-problem-in-scala-and-r/

More Related Content

What's hot

14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanupdhrubo kayal
 
Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...
hwbloom135
 
Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...
hwbloom121
 
Method parameters in c#
Method parameters in c#Method parameters in c#
Method parameters in c#
Dr.Neeraj Kumar Pandey
 
Templates
TemplatesTemplates
Effective Java - Always override toString() method
Effective Java - Always override toString() methodEffective Java - Always override toString() method
Effective Java - Always override toString() methodFerdous Mahmud Shaon
 
Struct
StructStruct
Struct
Fahuda E
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
Prabu U
 
Function
FunctionFunction
Function
Saniati
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
Pranali Chaudhari
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
Michael Heron
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
NUST Stuff
 
Function overloading
Function overloadingFunction overloading
Function overloading
Ashish Kelwa
 
Computer techniques for optimization of cycle of operations
Computer techniques for optimization of cycle of operationsComputer techniques for optimization of cycle of operations
Computer techniques for optimization of cycle of operations
Safdar Ali
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
Aakash Singh
 
5.program structure
5.program structure5.program structure
5.program structure
Shankar Gangaju
 
Functions in c
Functions in cFunctions in c
Functions in c
kalavathisugan
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
gourav kottawar
 
CSEG1001 Unit 5 Structure and Unions
CSEG1001 Unit 5 Structure and UnionsCSEG1001 Unit 5 Structure and Unions
CSEG1001 Unit 5 Structure and Unions
Dhiviya Rose
 

What's hot (20)

14 initialization & cleanup
14   initialization & cleanup14   initialization & cleanup
14 initialization & cleanup
 
Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...
 
Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...Write a List class to store Vehicle objects. The implementation of List will ...
Write a List class to store Vehicle objects. The implementation of List will ...
 
Method parameters in c#
Method parameters in c#Method parameters in c#
Method parameters in c#
 
Templates
TemplatesTemplates
Templates
 
Effective Java - Always override toString() method
Effective Java - Always override toString() methodEffective Java - Always override toString() method
Effective Java - Always override toString() method
 
Struct
StructStruct
Struct
 
Structures and Pointers
Structures and PointersStructures and Pointers
Structures and Pointers
 
Function
FunctionFunction
Function
 
Introduction to C++
Introduction to C++Introduction to C++
Introduction to C++
 
2CPP18 - Modifiers
2CPP18 - Modifiers2CPP18 - Modifiers
2CPP18 - Modifiers
 
Handout # 4 functions + scopes
Handout # 4   functions + scopes Handout # 4   functions + scopes
Handout # 4 functions + scopes
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Computer techniques for optimization of cycle of operations
Computer techniques for optimization of cycle of operationsComputer techniques for optimization of cycle of operations
Computer techniques for optimization of cycle of operations
 
Type Conversion, Precedence and Associativity
Type Conversion, Precedence and AssociativityType Conversion, Precedence and Associativity
Type Conversion, Precedence and Associativity
 
5.program structure
5.program structure5.program structure
5.program structure
 
Functions in c
Functions in cFunctions in c
Functions in c
 
Rrelational algebra in dbms overview
Rrelational algebra in dbms overviewRrelational algebra in dbms overview
Rrelational algebra in dbms overview
 
CSEG1001 Unit 5 Structure and Unions
CSEG1001 Unit 5 Structure and UnionsCSEG1001 Unit 5 Structure and Unions
CSEG1001 Unit 5 Structure and Unions
 
Unit 7: Built-In Functions
Unit 7: Built-In FunctionsUnit 7: Built-In Functions
Unit 7: Built-In Functions
 

Similar to Expression Problem in Scala

in C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdfin C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdf
adithyaups
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materials
gayaramesh
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG
Greg.Helton
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
BhushanLilhare
 
PEOPLESOFT PTF
PEOPLESOFT PTFPEOPLESOFT PTF
PEOPLESOFT PTF
Gautam Chaudhary
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
Naresh Jain
 
Use of Classes and functions#include iostreamusing name.docx
 Use of Classes and functions#include iostreamusing name.docx Use of Classes and functions#include iostreamusing name.docx
Use of Classes and functions#include iostreamusing name.docx
aryan532920
 
C programming session 09
C programming session 09C programming session 09
C programming session 09Dushmanta Nath
 
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docxInsert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
doylymaura
 
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docxInsert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
carliotwaycave
 
Tasks In this assignment you are required to design and imp.pdf
Tasks In this assignment you are required to design and imp.pdfTasks In this assignment you are required to design and imp.pdf
Tasks In this assignment you are required to design and imp.pdf
acsmadurai
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
Pooja Dixit
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!Anas Mohammed
 
Visualbasic tutorial
Visualbasic tutorialVisualbasic tutorial
Visualbasic tutorial
Andi Simanjuntak
 
Chapter 3.4
Chapter 3.4Chapter 3.4
Chapter 3.4sotlsoc
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
tjunicornfx
 
Keras and TensorFlow
Keras and TensorFlowKeras and TensorFlow
Keras and TensorFlow
NopphawanTamkuan
 
Cs 568 Spring 10 Lecture 5 Estimation
Cs 568 Spring 10  Lecture 5 EstimationCs 568 Spring 10  Lecture 5 Estimation
Cs 568 Spring 10 Lecture 5 Estimation
Lawrence Bernstein
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT
TheVerse1
 

Similar to Expression Problem in Scala (20)

in C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdfin C++ Design a class named Employee The class should keep .pdf
in C++ Design a class named Employee The class should keep .pdf
 
Unit iii vb_study_materials
Unit iii vb_study_materialsUnit iii vb_study_materials
Unit iii vb_study_materials
 
RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG RPG Program for Unit Testing RPG
RPG Program for Unit Testing RPG
 
59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx59_OOP_Function Template and multiple parameters.pptx
59_OOP_Function Template and multiple parameters.pptx
 
PEOPLESOFT PTF
PEOPLESOFT PTFPEOPLESOFT PTF
PEOPLESOFT PTF
 
TDD And Refactoring
TDD And RefactoringTDD And Refactoring
TDD And Refactoring
 
Use of Classes and functions#include iostreamusing name.docx
 Use of Classes and functions#include iostreamusing name.docx Use of Classes and functions#include iostreamusing name.docx
Use of Classes and functions#include iostreamusing name.docx
 
C programming session 09
C programming session 09C programming session 09
C programming session 09
 
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docxInsert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
 
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docxInsert Your Name and ClassIT Online Training (ITOT) Analys.docx
Insert Your Name and ClassIT Online Training (ITOT) Analys.docx
 
Tasks In this assignment you are required to design and imp.pdf
Tasks In this assignment you are required to design and imp.pdfTasks In this assignment you are required to design and imp.pdf
Tasks In this assignment you are required to design and imp.pdf
 
pl/sql Procedure
pl/sql Procedurepl/sql Procedure
pl/sql Procedure
 
My cool new Slideshow!
My cool new Slideshow!My cool new Slideshow!
My cool new Slideshow!
 
Operators
OperatorsOperators
Operators
 
Visualbasic tutorial
Visualbasic tutorialVisualbasic tutorial
Visualbasic tutorial
 
Chapter 3.4
Chapter 3.4Chapter 3.4
Chapter 3.4
 
Procedures functions structures in VB.Net
Procedures  functions  structures in VB.NetProcedures  functions  structures in VB.Net
Procedures functions structures in VB.Net
 
Keras and TensorFlow
Keras and TensorFlowKeras and TensorFlow
Keras and TensorFlow
 
Cs 568 Spring 10 Lecture 5 Estimation
Cs 568 Spring 10  Lecture 5 EstimationCs 568 Spring 10  Lecture 5 Estimation
Cs 568 Spring 10 Lecture 5 Estimation
 
9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT9. DBMS Experiment Laboratory PresentationPPT
9. DBMS Experiment Laboratory PresentationPPT
 

Recently uploaded

Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
manasideore6
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
Kamal Acharya
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
thanhdowork
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
BrazilAccount1
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
fxintegritypublishin
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
ClaraZara1
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
Neometrix_Engineering_Pvt_Ltd
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Dr.Costas Sachpazis
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
Kamal Acharya
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation & Control
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
gerogepatton
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Sreedhar Chowdam
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
ChristineTorrepenida1
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
ydteq
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
Robbie Edward Sayers
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Soumen Santra
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
top1002
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
aqil azizi
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
veerababupersonal22
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
SamSarthak3
 

Recently uploaded (20)

Fundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptxFundamentals of Electric Drives and its applications.pptx
Fundamentals of Electric Drives and its applications.pptx
 
Student information management system project report ii.pdf
Student information management system project report ii.pdfStudent information management system project report ii.pdf
Student information management system project report ii.pdf
 
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
RAT: Retrieval Augmented Thoughts Elicit Context-Aware Reasoning in Long-Hori...
 
AP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specificAP LAB PPT.pdf ap lab ppt no title specific
AP LAB PPT.pdf ap lab ppt no title specific
 
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdfHybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
Hybrid optimization of pumped hydro system and solar- Engr. Abdul-Azeez.pdf
 
6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)6th International Conference on Machine Learning & Applications (CMLA 2024)
6th International Conference on Machine Learning & Applications (CMLA 2024)
 
Standard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - NeometrixStandard Reomte Control Interface - Neometrix
Standard Reomte Control Interface - Neometrix
 
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
Sachpazis:Terzaghi Bearing Capacity Estimation in simple terms with Calculati...
 
Cosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdfCosmetic shop management system project report.pdf
Cosmetic shop management system project report.pdf
 
Water Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdfWater Industry Process Automation and Control Monthly - May 2024.pdf
Water Industry Process Automation and Control Monthly - May 2024.pdf
 
Immunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary AttacksImmunizing Image Classifiers Against Localized Adversary Attacks
Immunizing Image Classifiers Against Localized Adversary Attacks
 
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&BDesign and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
Design and Analysis of Algorithms-DP,Backtracking,Graphs,B&B
 
Unbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptxUnbalanced Three Phase Systems and circuits.pptx
Unbalanced Three Phase Systems and circuits.pptx
 
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
一比一原版(UofT毕业证)多伦多大学毕业证成绩单如何办理
 
HYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generationHYDROPOWER - Hydroelectric power generation
HYDROPOWER - Hydroelectric power generation
 
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTSHeap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
Heap Sort (SS).ppt FOR ENGINEERING GRADUATES, BCA, MCA, MTECH, BSC STUDENTS
 
Basic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparelBasic Industrial Engineering terms for apparel
Basic Industrial Engineering terms for apparel
 
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdfTutorial for 16S rRNA Gene Analysis with QIIME2.pdf
Tutorial for 16S rRNA Gene Analysis with QIIME2.pdf
 
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERSCW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
CW RADAR, FMCW RADAR, FMCW ALTIMETER, AND THEIR PARAMETERS
 
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdfAKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
AKS UNIVERSITY Satna Final Year Project By OM Hardaha.pdf
 

Expression Problem in Scala

  • 2. Agenda ➢ Introduction ➢ Set up a use case ➢ Proposed solution ➢ Talk about pros and cons ➢ Q/A
  • 3. Introduction 1/2 The expression problem is one in which the challenge is: ➢ Define a data type with cases. ➢ Add new cases of the type, and operations for the types. ➢ Avoid recompiling.
  • 4. Introduction 2/2 Any implementation of the expression problem should satisfy the following requirements: ➢ Extensibility in both dimensions. ➢ Strong static type safety. ➢ No modification of the existing code. ➢ Separate compilation.
  • 5. Use case 1/3 We are using a third party library case class Employee(name: String, id : Long) trait Payroll { def processEmployees(employees: Vector[Employee]): Either[String, Throwable] }
  • 6. Use case 2/3 We can easily add new types class USPayroll extends Payroll { def processEmployees(employees: Vector[Employee]) = Left("US payroll") } class JapanPayroll extends Payroll { def processEmployees(employees: Vector[Employee]) = Left("Japan payroll") }
  • 7. Use case 3/3 What if we need to add new operations on the types? E.g. Deal with Contractors trait ExtendedPayroll extends Payroll { def processEmployees(employees: Vector[Employee]): Either[String, Throwable] def processContractors(contractors: Vector[Contractor]): Either[String, Throwable] }
  • 9. This is a practical problem How to add features to an existing system incrementally without doing modifications?
  • 10. Proposed solution ➔ Leverage scala traits and abstract type members to solve the expression problem. ➔ Rewrite the same payroll system, so you can easily add new operations to it, without breaking type- safety, and at the same time add a new type.
  • 11. Some Code 1/5The new payroll system will be: trait PayrollSystem { case class Employee(name: String, id: Long) type P <: Payroll trait Payroll { def processEmployees(employees: Vector[Employee]): Either[String, Throwable] } def processPayroll(p: P): Either[String, Throwable] } // You nest everything inside a trait so that you can treat it as a module. // The type P denotes some subtype of the Payroll trait, // which declares an abstract method to process salaries for employees. // The processPayroll method needs to be implemented to process payrolls for a // given Payroll type.
  • 12. Some Code 2/5We can still easily add a new type trait USPayrollSystem extends PayrollSystem { class USPayroll extends Payroll { def processEmployees(employees: Vector[Employee]) = { println("US payroll") Left("US payroll") } } } PayrollSystem USPayrollSystem
  • 13. Some Code 3/5What about a new operation ? trait ContractorPayrollSystem extends PayrollSystem { case class Contractor(name: String) //Shadowing the Payroll trait defined in PayrollSystem trait Payroll extends super.Payroll { def processContractors(contractors: Vector[Contractor]): Either[String, Throwable] } } PayrollSystem USPayrollSystem ContractorPayrollSystem
  • 14. Some Code 4/5And ... trait USContractorPayrollSystem extends USPayrollSystem with ContractorPayrollSystem { //We are shadowing the former definition of USPayroll. class USPayroll extends super.USPayroll with Payroll { def processContractors(contractors: Vector[Contractor]) = { println("US contract payroll") Left("US contract payroll") } } } PayrollSystem USPayrollSystem ContractorPayrollSystem USContractorPayrollSystem
  • 15. Some Code 5/5Finally ... object USEmployeeAndContractorPayroll extends USContractorPayrollSystem { type P = USPayroll def processPayroll(p: USPayroll): Either[String, Throwable] = { p.processEmployees(Vector(Employee("a", 1))) p.processContractors(Vector(Contractor("b"))) Left("payroll processed successfully") } }
  • 16. Proposed solution This was a good example to demonstrate: – The power of Scala’s type system – The abstraction available to build scalable and extensible components
  • 17. We achieved a solution OP TYPE
  • 18. Pros And Cons – Inside the context, shadowing let you extend the old definition, without overriding it. – Shadowing can introduce unintended errors in your code.
  • 20. Some resources to get more details ❖ http://www.scala-lang.org/docu/files/TheExpressionProblem.pdf ❖ https://news.ycombinator.com/item?id=11683379 ❖ http://fileadmin.cs.lth.se/sde/people/gorel/misc/ExpProblemTalkPart1. pdf ❖ http://lambda-the-ultimate.org/node/3141 ❖ https://prezi.com/wwqo9dtgqhs2/comparing-solutions-to-the- expression-problem-in-scala-and-r/