SlideShare a Scribd company logo
1 of 12
Download to read offline
Types
A basic use case
Scenario
• Library for an API
• DELETE /api/users?query=colour:orange
• Result represents the operation
performed
Result format
200:
{
status: “SUCCESS”,
users: [
{
“name” : “R2E2”,
“email” : “magnifera@indica.com”
},
{
“email” : “secretly_a_carrot@veg.com”
}
]
Result format
400:
{
“status” : “FAILURE”,
“reason” : “Invalid query”
}
403:
{
“status”:“FAILURE”,
“reason”: “Permission denied”
}
Building a library
case class User(email: String, name: String)
case class Result(
status: String,
users: List[User],
reason: String
)
Implementation
def UserDecoder: DecodeJson[User] = DecodeJson(c => for {
email <- (c -- "email").as[Option[String]]
name <- (c -- "name").as[Option[String]]
} yield User(email.orNull, name.orNull))
def ResultCoder: DecodeJson[Result] = DecodeJson(c => for {
result <- (c -- "status").as[Option[String]]
users <- (c -- "users").as[Option[List[User]]]
reason <- (c -- "reason").as[Option[String]]
} yield ResultData(result.orNull, users.orNull, reason.orNull))
Usage
// case class Result(status: String, users: List[User], reason: String)
def happilyUsingMyResults(result: Result) = {
log(s"Result: ${result.status.toUpperCase}
Reason: ${result.reason.toUpperCase}")
result.users.foreach(
user => log(s"User email: ${user.email.toLowerCase}
User name: ${user.name}")
)
}
Null pointer exceptions everywhere!
Implementation with Options
case class User(email: String, name: Option[String])
case class Result(
status: String,
users: Option[List[User]],
reason: Option[String]
)
Is it any better?
def happilyUsingMyResults(result: Result) = {
val reason = result.reason.map(reason => s"Reason: $reason").getOrElse("")
println(s"Result: ${result.status.toUpperCase} - Reason: $reason")
result.users.foreach(
_.foreach(
user => {
val username = user.name.map(name => s"User name: $name").getOrElse("")
log(s"User email: ${user.email.toLowerCase} $username")
}
)
)
}
Typed implementation
case class User(email: String, name: Option[String])
sealed trait Result {
val status: String
}
case class Success(status: String, users: List[User]) extends Result
case class Failure(status: String, reason: String) extends Result
def happilyUsingMyResults(result: Result) = {
result match {
case Success(status, users) => {
log(s"Result: $status")
users.foreach(user => {
val usernameString =
user.name.map(name => s"User name: $name").getOrElse("")
log(s"User email: ${user.email.toLowerCase} $usernameString")
})
}
case Failure(status, reason) =>
log(s"Result: $status Reason: $reason")
}
}
TLDR;
• Use types to represent the state of your
program
• Unreachable states should not be
representable
• Handle these concerns at the borders

More Related Content

Similar to Types - ScalaSyd

More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weiboshaokun
 
Odoo Experience 2018 - Develop an App with the Odoo Framework
Odoo Experience 2018 - Develop an App with the Odoo FrameworkOdoo Experience 2018 - Develop an App with the Odoo Framework
Odoo Experience 2018 - Develop an App with the Odoo FrameworkElínAnna Jónasdóttir
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Rabble .
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30fiyuer
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecturepostrational
 
Nodejs functional programming and schema validation lightning talk
Nodejs   functional programming and schema validation lightning talkNodejs   functional programming and schema validation lightning talk
Nodejs functional programming and schema validation lightning talkDeepank Gupta
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responsesdarrelmiller71
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Rabble .
 
The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)ungerik
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperJon Kruger
 
Persistence with Ada Database Objects (ADO)
Persistence with Ada Database Objects (ADO)Persistence with Ada Database Objects (ADO)
Persistence with Ada Database Objects (ADO)Stephane Carrez
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsMike Subelsky
 
Building Web-API without Rails, Registration or SMS
Building Web-API without Rails, Registration or SMSBuilding Web-API without Rails, Registration or SMS
Building Web-API without Rails, Registration or SMSPivorak MeetUp
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperGiordano Scalzo
 
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJSAprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJSLoiane Groner
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)Ehtisham Ali
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsSalesforce Developers
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksShawn Rider
 
Seguranca em APP Rails
Seguranca em APP RailsSeguranca em APP Rails
Seguranca em APP RailsDaniel Lopes
 

Similar to Types - ScalaSyd (20)

More to RoC weibo
More to RoC weiboMore to RoC weibo
More to RoC weibo
 
Odoo Experience 2018 - Develop an App with the Odoo Framework
Odoo Experience 2018 - Develop an App with the Odoo FrameworkOdoo Experience 2018 - Develop an App with the Odoo Framework
Odoo Experience 2018 - Develop an App with the Odoo Framework
 
Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007Introduction to Active Record - Silicon Valley Ruby Conference 2007
Introduction to Active Record - Silicon Valley Ruby Conference 2007
 
How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30How to disassemble one monster app into an ecosystem of 30
How to disassemble one monster app into an ecosystem of 30
 
Scalable web application architecture
Scalable web application architectureScalable web application architecture
Scalable web application architecture
 
Nodejs functional programming and schema validation lightning talk
Nodejs   functional programming and schema validation lightning talkNodejs   functional programming and schema validation lightning talk
Nodejs functional programming and schema validation lightning talk
 
Crafting Evolvable Api Responses
Crafting Evolvable Api ResponsesCrafting Evolvable Api Responses
Crafting Evolvable Api Responses
 
Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007Introduction to Active Record at MySQL Conference 2007
Introduction to Active Record at MySQL Conference 2007
 
The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)The go-start webframework (GTUG Vienna 27.03.2012)
The go-start webframework (GTUG Vienna 27.03.2012)
 
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby DeveloperVenturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
Venturing Into The Wild: A .NET Developer's Experience As A Ruby Developer
 
Persistence with Ada Database Objects (ADO)
Persistence with Ada Database Objects (ADO)Persistence with Ada Database Objects (ADO)
Persistence with Ada Database Objects (ADO)
 
SproutCore and the Future of Web Apps
SproutCore and the Future of Web AppsSproutCore and the Future of Web Apps
SproutCore and the Future of Web Apps
 
Building Web-API without Rails, Registration or SMS
Building Web-API without Rails, Registration or SMSBuilding Web-API without Rails, Registration or SMS
Building Web-API without Rails, Registration or SMS
 
Tame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapperTame Accidental Complexity with Ruby and MongoMapper
Tame Accidental Complexity with Ruby and MongoMapper
 
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJSAprimorando sua Aplicação com Ext JS 4 - BrazilJS
Aprimorando sua Aplicação com Ext JS 4 - BrazilJS
 
What's new in Django 1.2?
What's new in Django 1.2?What's new in Django 1.2?
What's new in Django 1.2?
 
Sql server ___________session_18(stored procedures)
Sql server  ___________session_18(stored procedures)Sql server  ___________session_18(stored procedures)
Sql server ___________session_18(stored procedures)
 
Using the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service ClientsUsing the Tooling API to Generate Apex SOAP Web Service Clients
Using the Tooling API to Generate Apex SOAP Web Service Clients
 
Django Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, TricksDjango Forms: Best Practices, Tips, Tricks
Django Forms: Best Practices, Tips, Tricks
 
Seguranca em APP Rails
Seguranca em APP RailsSeguranca em APP Rails
Seguranca em APP Rails
 

Recently uploaded

Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Call Girls in Nagpur High Profile
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)simmis5
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Bookingdharasingh5698
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...SUHANI PANDEY
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdfKamal Acharya
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdfankushspencer015
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduitsrknatarajan
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performancesivaprakash250
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLManishPatel169454
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesPrabhanshu Chaturvedi
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Bookingroncy bisnoi
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spaintimesproduction05
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSrknatarajan
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college projectTonystark477637
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01KreezheaRecto
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756dollysharma2066
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTbhaskargani46
 

Recently uploaded (20)

Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...Top Rated  Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
Top Rated Pune Call Girls Budhwar Peth ⟟ 6297143586 ⟟ Call Me For Genuine Se...
 
Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)Java Programming :Event Handling(Types of Events)
Java Programming :Event Handling(Types of Events)
 
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 BookingVIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
VIP Call Girls Ankleshwar 7001035870 Whatsapp Number, 24/07 Booking
 
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
VIP Model Call Girls Kothrud ( Pune ) Call ON 8005736733 Starting From 5K to ...
 
Online banking management system project.pdf
Online banking management system project.pdfOnline banking management system project.pdf
Online banking management system project.pdf
 
AKTU Computer Networks notes --- Unit 3.pdf
AKTU Computer Networks notes ---  Unit 3.pdfAKTU Computer Networks notes ---  Unit 3.pdf
AKTU Computer Networks notes --- Unit 3.pdf
 
UNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular ConduitsUNIT-II FMM-Flow Through Circular Conduits
UNIT-II FMM-Flow Through Circular Conduits
 
UNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its PerformanceUNIT - IV - Air Compressors and its Performance
UNIT - IV - Air Compressors and its Performance
 
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELLPVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
PVC VS. FIBERGLASS (FRP) GRAVITY SEWER - UNI BELL
 
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort ServiceCall Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
Call Girls in Ramesh Nagar Delhi 💯 Call Us 🔝9953056974 🔝 Escort Service
 
Glass Ceramics: Processing and Properties
Glass Ceramics: Processing and PropertiesGlass Ceramics: Processing and Properties
Glass Ceramics: Processing and Properties
 
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance BookingCall Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
Call Girls Walvekar Nagar Call Me 7737669865 Budget Friendly No Advance Booking
 
Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024Water Industry Process Automation & Control Monthly - April 2024
Water Industry Process Automation & Control Monthly - April 2024
 
Roadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and RoutesRoadmap to Membership of RICS - Pathways and Routes
Roadmap to Membership of RICS - Pathways and Routes
 
Vivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design SpainVivazz, Mieres Social Housing Design Spain
Vivazz, Mieres Social Housing Design Spain
 
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICSUNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
UNIT-IFLUID PROPERTIES & FLOW CHARACTERISTICS
 
result management system report for college project
result management system report for college projectresult management system report for college project
result management system report for college project
 
Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01Double rodded leveling 1 pdf activity 01
Double rodded leveling 1 pdf activity 01
 
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
FULL ENJOY Call Girls In Mahipalpur Delhi Contact Us 8377877756
 
Generative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPTGenerative AI or GenAI technology based PPT
Generative AI or GenAI technology based PPT
 

Types - ScalaSyd

  • 2. Scenario • Library for an API • DELETE /api/users?query=colour:orange • Result represents the operation performed
  • 3. Result format 200: { status: “SUCCESS”, users: [ { “name” : “R2E2”, “email” : “magnifera@indica.com” }, { “email” : “secretly_a_carrot@veg.com” } ]
  • 4. Result format 400: { “status” : “FAILURE”, “reason” : “Invalid query” } 403: { “status”:“FAILURE”, “reason”: “Permission denied” }
  • 5. Building a library case class User(email: String, name: String) case class Result( status: String, users: List[User], reason: String )
  • 6. Implementation def UserDecoder: DecodeJson[User] = DecodeJson(c => for { email <- (c -- "email").as[Option[String]] name <- (c -- "name").as[Option[String]] } yield User(email.orNull, name.orNull)) def ResultCoder: DecodeJson[Result] = DecodeJson(c => for { result <- (c -- "status").as[Option[String]] users <- (c -- "users").as[Option[List[User]]] reason <- (c -- "reason").as[Option[String]] } yield ResultData(result.orNull, users.orNull, reason.orNull))
  • 7. Usage // case class Result(status: String, users: List[User], reason: String) def happilyUsingMyResults(result: Result) = { log(s"Result: ${result.status.toUpperCase} Reason: ${result.reason.toUpperCase}") result.users.foreach( user => log(s"User email: ${user.email.toLowerCase} User name: ${user.name}") ) } Null pointer exceptions everywhere!
  • 8. Implementation with Options case class User(email: String, name: Option[String]) case class Result( status: String, users: Option[List[User]], reason: Option[String] )
  • 9. Is it any better? def happilyUsingMyResults(result: Result) = { val reason = result.reason.map(reason => s"Reason: $reason").getOrElse("") println(s"Result: ${result.status.toUpperCase} - Reason: $reason") result.users.foreach( _.foreach( user => { val username = user.name.map(name => s"User name: $name").getOrElse("") log(s"User email: ${user.email.toLowerCase} $username") } ) ) }
  • 10. Typed implementation case class User(email: String, name: Option[String]) sealed trait Result { val status: String } case class Success(status: String, users: List[User]) extends Result case class Failure(status: String, reason: String) extends Result
  • 11. def happilyUsingMyResults(result: Result) = { result match { case Success(status, users) => { log(s"Result: $status") users.foreach(user => { val usernameString = user.name.map(name => s"User name: $name").getOrElse("") log(s"User email: ${user.email.toLowerCase} $usernameString") }) } case Failure(status, reason) => log(s"Result: $status Reason: $reason") } }
  • 12. TLDR; • Use types to represent the state of your program • Unreachable states should not be representable • Handle these concerns at the borders