SlideShare uma empresa Scribd logo
1 de 26
Baixar para ler offline
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.
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

Mais conteúdo relacionado

Mais procurados (20)

Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2Routing & Navigating Pages in Angular 2
Routing & Navigating Pages in Angular 2
 
SignalR with asp.net
SignalR with asp.netSignalR with asp.net
SignalR with asp.net
 
Remote Method Invocation in JAVA
Remote Method Invocation in JAVARemote Method Invocation in JAVA
Remote Method Invocation in JAVA
 
Soap vs rest
Soap vs restSoap vs rest
Soap vs rest
 
Advance Java Topics (J2EE)
Advance Java Topics (J2EE)Advance Java Topics (J2EE)
Advance Java Topics (J2EE)
 
Spring framework Controllers and Annotations
Spring framework   Controllers and AnnotationsSpring framework   Controllers and Annotations
Spring framework Controllers and Annotations
 
Angular 2.0 forms
Angular 2.0 formsAngular 2.0 forms
Angular 2.0 forms
 
Database connectivity in python
Database connectivity in pythonDatabase connectivity in python
Database connectivity in python
 
Print function in PHP
Print function in PHPPrint function in PHP
Print function in PHP
 
JavaScript Programming
JavaScript ProgrammingJavaScript Programming
JavaScript Programming
 
Hibernate architecture
Hibernate architectureHibernate architecture
Hibernate architecture
 
Implicit object.pptx
Implicit object.pptxImplicit object.pptx
Implicit object.pptx
 
Java Collections
Java  Collections Java  Collections
Java Collections
 
Java script
Java scriptJava script
Java script
 
Bootstrap Web Development Framework
Bootstrap Web Development FrameworkBootstrap Web Development Framework
Bootstrap Web Development Framework
 
Introduction To Angular's reactive forms
Introduction To Angular's reactive formsIntroduction To Angular's reactive forms
Introduction To Angular's reactive forms
 
Spring boot
Spring bootSpring boot
Spring boot
 
Error handling in ASP.NET
Error handling in ASP.NETError handling in ASP.NET
Error handling in ASP.NET
 
Fly Weight Design Pattern.pptx
Fly Weight Design Pattern.pptxFly Weight Design Pattern.pptx
Fly Weight Design Pattern.pptx
 

Destaque

Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collectionsKnoldus Inc.
 
Scala traits aug24-introduction
Scala traits aug24-introductionScala traits aug24-introduction
Scala traits aug24-introductionKnoldus Inc.
 
Thinking functional-in-scala
Thinking functional-in-scalaThinking functional-in-scala
Thinking functional-in-scalaKnoldus Inc.
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Futuremircodotta
 
37 Java Interview Questions
37 Java Interview Questions37 Java Interview Questions
37 Java Interview QuestionsArc & Codementor
 
Domain-driven design
Domain-driven designDomain-driven design
Domain-driven designKnoldus Inc.
 
OOPs Development with Scala
OOPs Development with ScalaOOPs Development with Scala
OOPs Development with ScalaKnoldus Inc.
 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State MachineKnoldus Inc.
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAMKnoldus Inc.
 

Destaque (10)

Scala style-guide
Scala style-guideScala style-guide
Scala style-guide
 
Scala parallel-collections
Scala parallel-collectionsScala parallel-collections
Scala parallel-collections
 
Scala traits aug24-introduction
Scala traits aug24-introductionScala traits aug24-introduction
Scala traits aug24-introduction
 
Thinking functional-in-scala
Thinking functional-in-scalaThinking functional-in-scala
Thinking functional-in-scala
 
Scala Past, Present & Future
Scala Past, Present & FutureScala Past, Present & Future
Scala Past, Present & Future
 
37 Java Interview Questions
37 Java Interview Questions37 Java Interview Questions
37 Java Interview Questions
 
Domain-driven design
Domain-driven designDomain-driven design
Domain-driven design
 
OOPs Development with Scala
OOPs Development with ScalaOOPs Development with Scala
OOPs Development with Scala
 
Akka Finite State Machine
Akka Finite State MachineAkka Finite State Machine
Akka Finite State Machine
 
Introduction to AWS IAM
Introduction to AWS IAMIntroduction to AWS IAM
Introduction to AWS IAM
 

Semelhante a Solid scala

Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with ScalaNeelkanth Sachdeva
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With ScalaKnoldus Inc.
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lispelliando dias
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Railsrstankov
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin Vasil Remeniuk
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy CodeNaresh Jain
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Pythondn
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play frameworkFelipe
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkIndicThreads
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Frameworkvhazrati
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & StreamsC4Media
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationEelco Visser
 

Semelhante a Solid scala (20)

Functional programming with Scala
Functional programming with ScalaFunctional programming with Scala
Functional programming with Scala
 
Functional Programming With Scala
Functional Programming With ScalaFunctional Programming With Scala
Functional Programming With Scala
 
Clojure - A new Lisp
Clojure - A new LispClojure - A new Lisp
Clojure - A new Lisp
 
Diifeerences In C#
Diifeerences In C#Diifeerences In C#
Diifeerences In C#
 
Effective PHP. Part 4
Effective PHP. Part 4Effective PHP. Part 4
Effective PHP. Part 4
 
00_Introduction to Java.ppt
00_Introduction to Java.ppt00_Introduction to Java.ppt
00_Introduction to Java.ppt
 
Ruby/Rails
Ruby/RailsRuby/Rails
Ruby/Rails
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
"Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin "Scala in Goozy", Alexey Zlobin
"Scala in Goozy", Alexey Zlobin
 
Design patterns
Design patternsDesign patterns
Design patterns
 
Working Effectively With Legacy Code
Working Effectively With Legacy CodeWorking Effectively With Legacy Code
Working Effectively With Legacy Code
 
Core java
Core javaCore java
Core java
 
14 operator overloading
14 operator overloading14 operator overloading
14 operator overloading
 
Patterns in Python
Patterns in PythonPatterns in Python
Patterns in Python
 
Short intro to scala and the play framework
Short intro to scala and the play frameworkShort intro to scala and the play framework
Short intro to scala and the play framework
 
Overview Of Lift Framework
Overview Of Lift FrameworkOverview Of Lift Framework
Overview Of Lift Framework
 
Overview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web FrameworkOverview of The Scala Based Lift Web Framework
Overview of The Scala Based Lift Web Framework
 
Scala based Lift Framework
Scala based Lift FrameworkScala based Lift Framework
Scala based Lift Framework
 
Lambdas & Streams
Lambdas & StreamsLambdas & Streams
Lambdas & Streams
 
TI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type ParameterizationTI1220 Lecture 8: Traits & Type Parameterization
TI1220 Lecture 8: Traits & Type Parameterization
 

Mais de Knoldus Inc.

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxKnoldus Inc.
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingKnoldus Inc.
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionKnoldus Inc.
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxKnoldus Inc.
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptxKnoldus Inc.
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfKnoldus Inc.
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxKnoldus Inc.
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingKnoldus Inc.
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesKnoldus Inc.
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxKnoldus Inc.
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxKnoldus Inc.
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxKnoldus Inc.
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxKnoldus Inc.
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxKnoldus Inc.
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationKnoldus Inc.
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationKnoldus Inc.
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIsKnoldus Inc.
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II PresentationKnoldus Inc.
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAKnoldus Inc.
 

Mais de Knoldus Inc. (20)

Supply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptxSupply chain security with Kubeclarity.pptx
Supply chain security with Kubeclarity.pptx
 
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML ParsingMastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
Mastering Web Scraping with JSoup Unlocking the Secrets of HTML Parsing
 
Akka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On IntroductionAkka gRPC Essentials A Hands-On Introduction
Akka gRPC Essentials A Hands-On Introduction
 
Entity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptxEntity Core with Core Microservices.pptx
Entity Core with Core Microservices.pptx
 
Introduction to Redis and its features.pptx
Introduction to Redis and its features.pptxIntroduction to Redis and its features.pptx
Introduction to Redis and its features.pptx
 
GraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdfGraphQL with .NET Core Microservices.pdf
GraphQL with .NET Core Microservices.pdf
 
NuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptxNuGet Packages Presentation (DoT NeT).pptx
NuGet Packages Presentation (DoT NeT).pptx
 
Data Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable TestingData Quality in Test Automation Navigating the Path to Reliable Testing
Data Quality in Test Automation Navigating the Path to Reliable Testing
 
K8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose KubernetesK8sGPTThe AI​ way to diagnose Kubernetes
K8sGPTThe AI​ way to diagnose Kubernetes
 
Introduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptxIntroduction to Circle Ci Presentation.pptx
Introduction to Circle Ci Presentation.pptx
 
Robusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptxRobusta -Tool Presentation (DevOps).pptx
Robusta -Tool Presentation (DevOps).pptx
 
Optimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptxOptimizing Kubernetes using GOLDILOCKS.pptx
Optimizing Kubernetes using GOLDILOCKS.pptx
 
Azure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptxAzure Function App Exception Handling.pptx
Azure Function App Exception Handling.pptx
 
CQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptxCQRS Design Pattern Presentation (Java).pptx
CQRS Design Pattern Presentation (Java).pptx
 
ETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake PresentationETL Observability: Azure to Snowflake Presentation
ETL Observability: Azure to Snowflake Presentation
 
Scripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics PresentationScripting with K6 - Beyond the Basics Presentation
Scripting with K6 - Beyond the Basics Presentation
 
Getting started with dotnet core Web APIs
Getting started with dotnet core Web APIsGetting started with dotnet core Web APIs
Getting started with dotnet core Web APIs
 
Introduction To Rust part II Presentation
Introduction To Rust part II PresentationIntroduction To Rust part II Presentation
Introduction To Rust part II Presentation
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
Configuring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRAConfiguring Workflows & Validators in JIRA
Configuring Workflows & Validators in JIRA
 

Último

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
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 FresherRemote DBA Services
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slidevu2urc
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 

Último (20)

Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
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
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Solid scala

  • 1. S.O.L.I.D with Scala Oct 23' 2012 > Vikas Hazrati > vikas@knoldus.com > @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.
  • 5.
  • 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