SlideShare a Scribd company logo
S.O.L.I.D with Scala

Oct 23' 2012 > Vikas Hazrati > vikas@knoldus.com > @vhazrati
what?


Five basic principles of object-oriented
programming and design.

When applied together intend to make it more likely that
a programmer will create a system that is easy
to maintain and extend over time.
problems


rigid – difficult to add new features

fragile – unable to identify the impact of the change

immobile – no reusability

viscous – going with the flow of bad practices already
  being present in the code.
solutions
loosely coupled – shouldn’t be too much of
  dependency between the modules, even if there is a
  dependency it should be via the interfaces and should
  be minimal.

cohesive code- The code has to be very specific in its
  operations.

context independent code- so that it can be reused.

DRY – Don't repeat yourself – Avoid copy-paste of
 code. Change in the code would have to be made in
 all the places where its been copied.
Solid scala
single responsibility principle - srp

a module should have only one reason to change




 Avoid side effects        Minimize code          Increase re-usability
                            touch-points



Separate out different responsibilities into different code units
package com.knolx

trait UserService {

    def changeEmail

}


class SettingUpdateService extends UserService {

    def changeEmail ={
      checkAccess match {
        case Some(x) => // do something
        case None => //do something else
      }
    }

    def checkAccess:Option[Any] = None

}
class task{

    def downloadFile = {}

    def parseFile = {}

    def persistData = {}
}
for scala



        srp applies to

          functions
       data structures
packages/ modules of functions
open closed principle - ocp


A module should be open for extension but
  closed for modification




     Avoid side effects   Minimize code
                           touch-points
case class Check(id:Int, bankName:String,
amount:Double)

class CheckProcessor {
  val checkList:List[Check] = List(new Check(1,
"BoA", 200.0))

    def checkProcessor = sendEmail

    def sendEmail = {}
}
case class Check(id:Int, bankName:String, amount:Double)

class CheckProcessor {
  val checkList:List[Check] = List(new Check(1, "BoA",
200.0), new Check(2, "Citi", 100.0))

  def checkProcessor = for (check <-checkList) if
(check.bankName == "BoA") sendEmail else sendFax

    def sendEmail = {}
    def sendFax = {}
}
trait   BankProcess{
  def   processCheck
}
class   BoABank(name:String) extends BankProcess{
  def   processCheck = sendEmail
  def   sendEmail = {}
}

class CitiBank(name:String) extends BankProcess{
  def processCheck = sendFax
  def sendFax = {}
}

case class Check(id:Int, bank:BankProcess, amount:Double)

class CheckProcessor {
  val checkList:List[Check] = List(new Check(1, new
BoABank("BoA"), 200.0), new Check(2, new CitiBank("Citi"),
100.0))

  def checkProcessor = for (check <-checkList)
check.bank.processCheck
}
interface segregation principle - isp


many specific interfaces are better than one
        general purpose interface




 Avoid side effects              Increase re-usability
trait   DoorService{
  def   isOpen
  def   open
  def   close
}

class   Door extends DoorService{
  def   isOpen = {}
  def   open = {}
  def   close = {}
}
trait   DoorService{
  def   isOpen
  def   open
  def   close
}

trait TimerDoorService{
  def closeAfterMinutes(duration:Int)
}

class   Door extends DoorService{
  def   isOpen = {}
  def   open = {}
  def   close = {}
}

class   TimerDoor extends DoorService with TimerDoorService{
  def   isOpen = {}
  def   open = {}
  def   close = {}
  def   closeAfterMinutes(duration:Int) = {}
}
dependency inversion principle - dip


depend on abstractions, not on concretions

Avoid side effects    reduced effort for     Increase re-usability
                     adjusting to existing
                         code changes
class TwitterProcessor {
  def processTweets = new Processor.process(List("1","2"))
}

class Processor {
  def process(list:List[String]) = {}
}
trait ProcessorService {
  def process(list:List[String])
}

class TwitterProcessor {
  val myProcessor:ProcessorService = new Processor
  def processTweets = myProcessor.process(List("1","2"))
}

class Processor extends ProcessorService{
  def process(list:List[String]) = process(list, true)
  def process(list:List[String], someCheck:Boolean) = {}
}
for scala




  becomes less relevant for Scala as we can
pass higher order functions to achieve the same
                    behavior
liskov substitution principle - lsp

 subclasses should be substitutable for their base
   classes


                            Avoid side effects

a derived class is substitutable for its base class if:

1. Its preconditions are no stronger than the base class method.
2. Its postconditions are no weaker than the base class method.
Or, in other words, derived methods should expect no more and provide no less
trait DogBehavior{
  def run
}

class RealDog extends DogBehavior{
  def run = {println("run")}
}

class ToyDog extends DogBehavior{
  val batteryPresent = true
  def run = {
    if (batteryPresent) println("run")
  }
}

object client {
def runTheDog(dog:DogBehavior) = {dog.run}
}
object client2 {
  def runTheDog(dog:DogBehavior) = {if (dog.isInstanceOf[ToyDog] )
dog.asInstanceOf[ToyDog].batteryPresent=true; dog.run}
}




           violates
             ocp
             now
Solid scala
Solid scala
Solid scala

More Related Content

What's hot (20)

PDF
Algorithms Lecture 3: Analysis of Algorithms II
Mohamed Loey
 
PPT
Writing Basic SQL SELECT Statements
Salman Memon
 
PPT
Skip list vinay khimsuriya_200430723005
vinaykhimsuriya1
 
PDF
abc032
AtCoder Inc.
 
PPTX
Divide and conquer 1
Kumar
 
PDF
ΠΛΗ30 ΜΑΘΗΜΑ 5.4
Dimitris Psounis
 
PPTX
Oracle: Joins
oracle content
 
PPTX
Encoders and decoders
Gaditek
 
PPTX
Combinational Logic Circuit
GargiKhanna1
 
PPTX
Chap ii.BCD code,Gray code
Bala Ganesh
 
PPTX
Universal turing coastus
Shiraz316
 
DOCX
CSC 433 Sample normalization SQL Question
Shakila Mahjabin
 
PDF
AtCoder Regular Contest 023 解説
AtCoder Inc.
 
PPT
Asymptotic Notation and Complexity
Rajandeep Gill
 
PDF
Karnaugh map
chandkec
 
PDF
8051,chapter1,architecture and peripherals
amrutachintawar239
 
PPT
Greedy method
Dr Shashikant Athawale
 
PPTX
AtCoder Regular Contest 029 解説
AtCoder Inc.
 
PDF
第21回アルゴリズム勉強会
Yuuki Ono
 
PPSX
Number system
Gagan Deep
 
Algorithms Lecture 3: Analysis of Algorithms II
Mohamed Loey
 
Writing Basic SQL SELECT Statements
Salman Memon
 
Skip list vinay khimsuriya_200430723005
vinaykhimsuriya1
 
abc032
AtCoder Inc.
 
Divide and conquer 1
Kumar
 
ΠΛΗ30 ΜΑΘΗΜΑ 5.4
Dimitris Psounis
 
Oracle: Joins
oracle content
 
Encoders and decoders
Gaditek
 
Combinational Logic Circuit
GargiKhanna1
 
Chap ii.BCD code,Gray code
Bala Ganesh
 
Universal turing coastus
Shiraz316
 
CSC 433 Sample normalization SQL Question
Shakila Mahjabin
 
AtCoder Regular Contest 023 解説
AtCoder Inc.
 
Asymptotic Notation and Complexity
Rajandeep Gill
 
Karnaugh map
chandkec
 
8051,chapter1,architecture and peripherals
amrutachintawar239
 
Greedy method
Dr Shashikant Athawale
 
AtCoder Regular Contest 029 解説
AtCoder Inc.
 
第21回アルゴリズム勉強会
Yuuki Ono
 
Number system
Gagan Deep
 

Viewers also liked (10)

PDF
Scala style-guide
Knoldus Inc.
 
PDF
Scala parallel-collections
Knoldus Inc.
 
PDF
Scala traits aug24-introduction
Knoldus Inc.
 
PDF
Thinking functional-in-scala
Knoldus Inc.
 
PDF
Scala Past, Present & Future
mircodotta
 
PDF
37 Java Interview Questions
Arc & Codementor
 
PDF
Domain-driven design
Knoldus Inc.
 
PDF
OOPs Development with Scala
Knoldus Inc.
 
ODP
Akka Finite State Machine
Knoldus Inc.
 
ODP
Introduction to AWS IAM
Knoldus Inc.
 
Scala style-guide
Knoldus Inc.
 
Scala parallel-collections
Knoldus Inc.
 
Scala traits aug24-introduction
Knoldus Inc.
 
Thinking functional-in-scala
Knoldus Inc.
 
Scala Past, Present & Future
mircodotta
 
37 Java Interview Questions
Arc & Codementor
 
Domain-driven design
Knoldus Inc.
 
OOPs Development with Scala
Knoldus Inc.
 
Akka Finite State Machine
Knoldus Inc.
 
Introduction to AWS IAM
Knoldus Inc.
 
Ad

Similar to Solid scala (20)

ODP
Functional programming with Scala
Neelkanth Sachdeva
 
ODP
Functional Programming With Scala
Knoldus Inc.
 
PDF
Clojure - A new Lisp
elliando dias
 
DOCX
Diifeerences In C#
rohit_gupta_mrt
 
PDF
Effective PHP. Part 4
Vasily Kartashov
 
PPT
00_Introduction to Java.ppt
HongAnhNguyn285885
 
KEY
Ruby/Rails
rstankov
 
PDF
Scala for Java Programmers
Eric Pederson
 
PPT
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
PDF
Design patterns
Anas Alpure
 
PPT
Working Effectively With Legacy Code
Naresh Jain
 
PPT
Core java
kasaragaddaslide
 
PPT
14 operator overloading
Docent Education
 
ODP
Patterns in Python
dn
 
PDF
Short intro to scala and the play framework
Felipe
 
PDF
Overview of The Scala Based Lift Web Framework
IndicThreads
 
PDF
Scala based Lift Framework
vhazrati
 
PDF
Overview Of Lift Framework
Xebia IT Architects
 
PDF
Lambdas & Streams
C4Media
 
PDF
TI1220 Lecture 8: Traits & Type Parameterization
Eelco Visser
 
Functional programming with Scala
Neelkanth Sachdeva
 
Functional Programming With Scala
Knoldus Inc.
 
Clojure - A new Lisp
elliando dias
 
Diifeerences In C#
rohit_gupta_mrt
 
Effective PHP. Part 4
Vasily Kartashov
 
00_Introduction to Java.ppt
HongAnhNguyn285885
 
Ruby/Rails
rstankov
 
Scala for Java Programmers
Eric Pederson
 
"Scala in Goozy", Alexey Zlobin
Vasil Remeniuk
 
Design patterns
Anas Alpure
 
Working Effectively With Legacy Code
Naresh Jain
 
Core java
kasaragaddaslide
 
14 operator overloading
Docent Education
 
Patterns in Python
dn
 
Short intro to scala and the play framework
Felipe
 
Overview of The Scala Based Lift Web Framework
IndicThreads
 
Scala based Lift Framework
vhazrati
 
Overview Of Lift Framework
Xebia IT Architects
 
Lambdas & Streams
C4Media
 
TI1220 Lecture 8: Traits & Type Parameterization
Eelco Visser
 
Ad

More from Knoldus Inc. (20)

PPTX
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
PPTX
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
PPTX
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
PPTX
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
PPTX
Java 17 features and implementation.pptx
Knoldus Inc.
 
PPTX
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
PPTX
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
PPTX
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
PPTX
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
PPTX
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
PPTX
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
PPTX
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
PPTX
Intro to Azure Container App Presentation
Knoldus Inc.
 
PPTX
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
PPTX
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
PPTX
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
PPTX
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
PPTX
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
PPTX
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
PPTX
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 
Angular Hydration Presentation (FrontEnd)
Knoldus Inc.
 
Optimizing Test Execution: Heuristic Algorithm for Self-Healing
Knoldus Inc.
 
Self-Healing Test Automation Framework - Healenium
Knoldus Inc.
 
Kanban Metrics Presentation (Project Management)
Knoldus Inc.
 
Java 17 features and implementation.pptx
Knoldus Inc.
 
Chaos Mesh Introducing Chaos in Kubernetes
Knoldus Inc.
 
GraalVM - A Step Ahead of JVM Presentation
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
Nomad by HashiCorp Presentation (DevOps)
Knoldus Inc.
 
DAPR - Distributed Application Runtime Presentation
Knoldus Inc.
 
Introduction to Azure Virtual WAN Presentation
Knoldus Inc.
 
Introduction to Argo Rollouts Presentation
Knoldus Inc.
 
Intro to Azure Container App Presentation
Knoldus Inc.
 
Insights Unveiled Test Reporting and Observability Excellence
Knoldus Inc.
 
Introduction to Splunk Presentation (DevOps)
Knoldus Inc.
 
Code Camp - Data Profiling and Quality Analysis Framework
Knoldus Inc.
 
AWS: Messaging Services in AWS Presentation
Knoldus Inc.
 
Amazon Cognito: A Primer on Authentication and Authorization
Knoldus Inc.
 
ZIO Http A Functional Approach to Scalable and Type-Safe Web Development
Knoldus Inc.
 
Managing State & HTTP Requests In Ionic.
Knoldus Inc.
 

Recently uploaded (20)

PDF
Staying Human in a Machine- Accelerated World
Catalin Jora
 
PDF
Advancing WebDriver BiDi support in WebKit
Igalia
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
July Patch Tuesday
Ivanti
 
PDF
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
DOCX
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
PDF
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PPTX
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
PPTX
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 
Staying Human in a Machine- Accelerated World
Catalin Jora
 
Advancing WebDriver BiDi support in WebKit
Igalia
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
July Patch Tuesday
Ivanti
 
Go Concurrency Real-World Patterns, Pitfalls, and Playground Battles.pdf
Emily Achieng
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Cryptography Quiz: test your knowledge of this important security concept.
Rajni Bhardwaj Grover
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
Transforming Utility Networks: Large-scale Data Migrations with FME
Safe Software
 
What Makes Contify’s News API Stand Out: Key Features at a Glance
Contify
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Achieving Consistent and Reliable AI Code Generation - Medusa AI
medusaaico
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Webinar: Introduction to LF Energy EVerest
DanBrown980551
 
Building Search Using OpenSearch: Limitations and Workarounds
Sease
 

Solid scala

  • 1. S.O.L.I.D with Scala Oct 23' 2012 > Vikas Hazrati > [email protected] > @vhazrati
  • 2. what? Five basic principles of object-oriented programming and design. When applied together intend to make it more likely that a programmer will create a system that is easy to maintain and extend over time.
  • 3. problems rigid – difficult to add new features fragile – unable to identify the impact of the change immobile – no reusability viscous – going with the flow of bad practices already being present in the code.
  • 4. solutions loosely coupled – shouldn’t be too much of dependency between the modules, even if there is a dependency it should be via the interfaces and should be minimal. cohesive code- The code has to be very specific in its operations. context independent code- so that it can be reused. DRY – Don't repeat yourself – Avoid copy-paste of code. Change in the code would have to be made in all the places where its been copied.
  • 6. single responsibility principle - srp a module should have only one reason to change Avoid side effects Minimize code Increase re-usability touch-points Separate out different responsibilities into different code units
  • 7. package com.knolx trait UserService { def changeEmail } class SettingUpdateService extends UserService { def changeEmail ={ checkAccess match { case Some(x) => // do something case None => //do something else } } def checkAccess:Option[Any] = None }
  • 8. class task{ def downloadFile = {} def parseFile = {} def persistData = {} }
  • 9. for scala srp applies to functions data structures packages/ modules of functions
  • 10. open closed principle - ocp A module should be open for extension but closed for modification Avoid side effects Minimize code touch-points
  • 11. case class Check(id:Int, bankName:String, amount:Double) class CheckProcessor { val checkList:List[Check] = List(new Check(1, "BoA", 200.0)) def checkProcessor = sendEmail def sendEmail = {} }
  • 12. case class Check(id:Int, bankName:String, amount:Double) class CheckProcessor { val checkList:List[Check] = List(new Check(1, "BoA", 200.0), new Check(2, "Citi", 100.0)) def checkProcessor = for (check <-checkList) if (check.bankName == "BoA") sendEmail else sendFax def sendEmail = {} def sendFax = {} }
  • 13. trait BankProcess{ def processCheck } class BoABank(name:String) extends BankProcess{ def processCheck = sendEmail def sendEmail = {} } class CitiBank(name:String) extends BankProcess{ def processCheck = sendFax def sendFax = {} } case class Check(id:Int, bank:BankProcess, amount:Double) class CheckProcessor { val checkList:List[Check] = List(new Check(1, new BoABank("BoA"), 200.0), new Check(2, new CitiBank("Citi"), 100.0)) def checkProcessor = for (check <-checkList) check.bank.processCheck }
  • 14. interface segregation principle - isp many specific interfaces are better than one general purpose interface Avoid side effects Increase re-usability
  • 15. trait DoorService{ def isOpen def open def close } class Door extends DoorService{ def isOpen = {} def open = {} def close = {} }
  • 16. trait DoorService{ def isOpen def open def close } trait TimerDoorService{ def closeAfterMinutes(duration:Int) } class Door extends DoorService{ def isOpen = {} def open = {} def close = {} } class TimerDoor extends DoorService with TimerDoorService{ def isOpen = {} def open = {} def close = {} def closeAfterMinutes(duration:Int) = {} }
  • 17. dependency inversion principle - dip depend on abstractions, not on concretions Avoid side effects reduced effort for Increase re-usability adjusting to existing code changes
  • 18. class TwitterProcessor { def processTweets = new Processor.process(List("1","2")) } class Processor { def process(list:List[String]) = {} }
  • 19. trait ProcessorService { def process(list:List[String]) } class TwitterProcessor { val myProcessor:ProcessorService = new Processor def processTweets = myProcessor.process(List("1","2")) } class Processor extends ProcessorService{ def process(list:List[String]) = process(list, true) def process(list:List[String], someCheck:Boolean) = {} }
  • 20. for scala becomes less relevant for Scala as we can pass higher order functions to achieve the same behavior
  • 21. liskov substitution principle - lsp subclasses should be substitutable for their base classes Avoid side effects a derived class is substitutable for its base class if: 1. Its preconditions are no stronger than the base class method. 2. Its postconditions are no weaker than the base class method. Or, in other words, derived methods should expect no more and provide no less
  • 22. trait DogBehavior{ def run } class RealDog extends DogBehavior{ def run = {println("run")} } class ToyDog extends DogBehavior{ val batteryPresent = true def run = { if (batteryPresent) println("run") } } object client { def runTheDog(dog:DogBehavior) = {dog.run} }
  • 23. object client2 { def runTheDog(dog:DogBehavior) = {if (dog.isInstanceOf[ToyDog] ) dog.asInstanceOf[ToyDog].batteryPresent=true; dog.run} } violates ocp now