SlideShare a Scribd company logo
1 of 24
   Modular Programming 
              Using Object in Scala


                                         Ruchi Jindal
                                      Software Consultant     
                                           Knoldus
Scala's Strength
   Agile, with lightweight syntax

   Scala is a pure object-oriented language

   Functional Programming

   Safe and performant, with strong static typing

   Functions are objects

   Everything is an object(Numbers are objects)

    1 + 2 * 3 / x ====> (1).+(((2).*(3))./(x))
Scala Says
“If I were to pick a language to use today other than Java, it would be
Scala.”

                                - James Gosling, creator of Java

“Scala, it must be stated, is the current heir apparent to the Java
throne. No other language on the JVM seems as capable of being a
"replacement for Java" as Scala, and the momentum behind Scala is
now unquestionable. While Scala is not a dynamic language, it has
many of the characteristics of popular dynamic languages, through its
rich and flexible type system, its sparse and clean syntax, and its
marriage of functional and object paradigms.”

                               - Charles Nutter, creator of JRuby

“I can honestly say if someone had shown me the Programming in
Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003
I'd probably have never created Groovy.”

                             - James Strachan, creator of Groovy.
Why unify FP and OOP?
            Both have complementary strengths for composition:

Functional programming:                   Object-oriented programming:


Makes it easy to build interesting     Makes it easy to adapt and extend
things from simple parts, using       complex systems, using
• higher-order functions,             • subtyping and inheritance,
• algebraic types and                 • dynamic configurations,
 pattern matching,                    • classes as partial abstractions.
 • parametric polymorphism.
Modular programming

   Also known as top down design and stepwise refinement.
   A software design technique that increases the extent to which software
    is composed of separate, interchangeable components called modules
    by breaking down program functions into modules, each of which
    accomplishes one function and contains everything necessary to
    accomplish this.
   Conceptually, modules represent a separation of concerns, and improve
    maintainability by enforcing logical boundaries between components.
   Modules are typically incorporated into the program through interfaces.
Why Need Modular Approach
Scala is a scalable language because we can use the same techniques to
construct small as well as large programs.

Programming in the large means organizing and assembling the smaller
pieces into larger programs, applications, or systems.

While the division of programs into packages is already quite helpful, it
is limited because it provides no way to abstract.

We cannot reconfigure a package two different ways within the same
program, and you cannot inherit between packages.

A package always includes one precise list of contents, and that list is
fixed until you change the code.


                            ................................
Why we need Modular Approach.......
Firstly there should be a module construct that provides
a good separation of interface and implementation.

Secondly, there should be a way to replace one module with another that
has the same interface with out changing or recompiling the modules that
depend on the replaced one.

Lastly, there should be a way to wire modules together. This wiring task
can by thought of as configuring the system.
How To achieve Modular Approach
   How to use Scala’s object-oriented features to make a program more
    modular

   How a simple singleton object can be used as a module

   How to use traits and classes as abstractions over modules. These
    abstractions can be reconfigured into multiple modules, even multiple
    times within the same program.

   How to use traits to divide a module across multiple files
To Build an enterprise web application you need the partition of the
software into layers, including

➔ a domain layer
➔ an application layer




 In the domain layer, we define domain objects, which will capture business
concepts and rules and encapsulate state that will be persisted to an
external relational database.

In the application layer, we’ll provide an API organized in terms of the
services ,the application offers to clients (including the user interface layer).

The application layer will implement these services by coordinating tasks
and delegatingthe work to the objects of the domain layer.
Lets Start with an Example
An Enterprise web application that will allow users to manage recipes.

It will contains two entities that will be persisted in the database.

➔ Food
➔ Recipe




    abstract class Food(val name: String) {
    override def toString = name
    }

    class Recipe(val name: String,val ingredients: List[Food],val instructions:
    String) {
    override def toString = name
    }
Here are some singleton instances of Food and Recipe classes, which can
be used when writing tests:

object Apple extends Food("Apple")
object Orange extends Food("Orange")
object Cream extends Food("Cream")
object Sugar extends Food("Sugar")

object FruitSalad extends Recipe("fruit salad",List(Apple, Orange, Cream,
Sugar),"Stir it all together.")
Scala uses objects for modules, so to modularize program we are making
two singleton objects to serve as the mock implementations of the
database and browser modules during testing.

object SimpleDatabase {
def allFoods = List(Apple, Orange, Cream, Sugar)
def foodNamed(name: String): Option[Food] =
allFoods.find(_.name == name)
def allRecipes: List[Recipe] = List(FruitSalad)
}
object SimpleBrowser {
def recipesUsing(food: Food) =
SimpleDatabase.allRecipes.filter(recipe =>
recipe.ingredients.contains(food))
}
You can use this database and browser as follows:

scala> val apple = SimpleDatabase.foodNamed("Apple").get
apple: Food = Apple

scala> SimpleBrowser.recipesUsing(apple)
res0: List[Recipe] = List(fruit salad)

To make things a little more interesting, suppose the database sorts foods
into categories. To implement this, you can add a FoodCategory class and a
list of all categories in the database.

eg. class FoodCategory(name: String, foods: List[Food])
object SimpleDatabase {

def allFoods = List(Apple, Orange, Cream, Sugar)

def foodNamed(name: String): Option[Food] =
allFoods.find(_.name == name)

def allRecipes: List[Recipe] = List(FruitSalad)

case class FoodCategory(name: String, foods: List[Food])

private var categories = List(
FoodCategory("fruits", List(Apple, Orange)),
FoodCategory("misc", List(Cream, Sugar)))

def allCategories = categories
}
object SimpleBrowser {
def recipesUsing(food: Food) =
SimpleDatabase.allRecipes.filter(recipe =>
recipe.ingredients.contains(food))
def displayCategory(category: SimpleDatabase.FoodCategory) {
println(category)
}}
Abstraction
The SimpleBrowser module mentions the SimpleDatabase mod-
ule by name, you won’t be able to plug in a different implementation of the
database module without modifying and recompiling the browser module.
In addition, although there’s no hard link from the SimpleDatabase
moduleto the SimpleBrowser module,there’s no clear way to enable the
user interface layer, for example, to be configured to use different
implementations of the browser module.

abstract class Browser {
  val database: Database

     def recipesUsing(food: Food) =
      database.allRecipes.filter(recipe =>
       recipe.ingredients.contains(food))

     def displayCategory(category: database.FoodCategory) {
       println(category)
     }
 }
abstract class Database {
    def allFoods: List[Food]
    def allRecipes: List[Recipe]

     def foodNamed(name: String) =
       allFoods.find(f => f.name == name)
     case class FoodCategory(name: String, foods: List[Food])
     def allCategories: List[FoodCategory]
 }

object SimpleDatabase extends Database {
    def allFoods = List(Apple, Orange, Cream, Sugar)

     def allRecipes: List[Recipe] = List(FruitSalad)

     private var categories = List(
       FoodCategory("fruits", List(Apple, Orange)),
       FoodCategory("misc", List(Cream, Sugar)))

     def allCategories = categories
 }
object SimpleBrowser extends Browser {
    val database = SimpleDatabase
  }


 scala> val apple = SimpleDatabase.foodNamed("Apple").get
 apple: Food = Apple

 scala> SimpleBrowser.recipesUsing(apple)
 res1: List[Recipe] = List(fruit salad)
Now we create a second mock database, and use the same
browser class with it



object StudentDatabase extends Database {
    object FrozenFood extends Food("FrozenFood")
    object HeatItUp extends Recipe(
      "heat it up",
      List(FrozenFood),
      "Microwave the 'food' for 10 minutes.")
    def allFoods = List(FrozenFood)
    def allRecipes = List(HeatItUp)
    def allCategories = List(
      FoodCategory("edible", List(FrozenFood)))
  }
  object StudentBrowser extends Browser {
    val database = StudentDatabase
  }
Splitting modules into traits
Often a module is too large to fit comfortably into a single file. When that
happens, you can use traits to split a module into separate files. For
example ,suppose you wanted to move categorization code out of the
main Database file and into its own.

trait FoodCategories {
case class FoodCategory(name: String, foods: List[Food])
def allCategories: List[FoodCategory]
}

Now class Database can mix in the FoodCategories trait instead of defin-
ing FoodCategory and allCategories itself
abstract class Database extends FoodCategories {
def allFoods: List[Food]
def allRecipes: List[Recipe]
def foodNamed(name: String) =
allFoods.find(f => f.name == name)
}
Continuing in this way, you might try and divide SimpleDatabase into
two traits, one for foods and one for recipes.

object SimpleDatabase extends Database
with SimpleFoods with SimpleRecipes

The SimpleFoods trait could look as :

trait SimpleFoods {
object Pear extends Food("Pear")
def allFoods = List(Apple, Pear)
def allCategories = Nil
}
Runtime linking
One final feature of Scala modules is worth emphasizing: they can be linked
together at runtime, and you can decide which modules will link to which
depending on runtime computations.

object GotApples {
def main(args: Array[String]) {
val db: Database =
if(args(0) == "student")
StudentDatabase
else
SimpleDatabase
object browser extends Browser {
val database = db
}
val apple = SimpleDatabase.foodNamed("Apple").get
for(recipe <- browser.recipesUsing(apple))
println(recipe)
}
}
if you use the simple database, you will find a recipe for fruit salad. If
you use the student database, you will find no recipes at all using apples:


$ scala GotApples simple
fruit salad
$ scala GotApples student
$//No output
Tracking module instances
Despite using the same code, the different browser and database modules cre-
ated in the previous section really are separate modules. This means that each
module has its own contents, including any nested classes. FoodCategory
in SimpleDatabase, for example, is a different class from FoodCategory
in StudentDatabase!

scala> val category = StudentDatabase.allCategories.head
category: StudentDatabase.FoodCategory =
FoodCategory(edible,List(FrozenFood))
scala> SimpleBrowser.displayCategory(category)
<console>:12: error: type mismatch;
found
: StudentDatabase.FoodCategory
required: SimpleBrowser.database.FoodCategory
SimpleBrowser.displayCategory(category)
ˆ
If we want all FoodCategorys to be the same, we can accomplish
this by moving the definition of FoodCategory outside of any class or trait.
Modular programming Using Object in Scala

More Related Content

What's hot

Functional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayFunctional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaVladimir Kostyukov
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...Philip Schwarz
 
Flash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with CoscoFlash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with CoscoDatabricks
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsPhilip Schwarz
 
The Object Model
The Object Model  The Object Model
The Object Model yndaravind
 
Understanding Java Garbage Collection
Understanding Java Garbage CollectionUnderstanding Java Garbage Collection
Understanding Java Garbage CollectionAzul Systems Inc.
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022Alexander Ioffe
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internalsKostas Tzoumas
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To ScalaPhilip Schwarz
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Philip Schwarz
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type ClassesJohn De Goes
 
Helm - Package manager in K8S
Helm - Package manager in K8SHelm - Package manager in K8S
Helm - Package manager in K8SPiotr Perzyna
 
Arriving at monads by going from pure-function composition to effectful-funct...
Arriving at monads by going from pure-function composition to effectful-funct...Arriving at monads by going from pure-function composition to effectful-funct...
Arriving at monads by going from pure-function composition to effectful-funct...Philip Schwarz
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scaladatamantra
 
Presentación open closed principle
Presentación open closed principlePresentación open closed principle
Presentación open closed principleAutentia
 
Deep Dive into Spark
Deep Dive into SparkDeep Dive into Spark
Deep Dive into SparkEric Xiao
 

What's hot (20)

Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Functional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayFunctional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 Way
 
Purely Functional Data Structures in Scala
Purely Functional Data Structures in ScalaPurely Functional Data Structures in Scala
Purely Functional Data Structures in Scala
 
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
Flash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with CoscoFlash for Apache Spark Shuffle with Cosco
Flash for Apache Spark Shuffle with Cosco
 
Monad as functor with pair of natural transformations
Monad as functor with pair of natural transformationsMonad as functor with pair of natural transformations
Monad as functor with pair of natural transformations
 
The Object Model
The Object Model  The Object Model
The Object Model
 
Understanding Java Garbage Collection
Understanding Java Garbage CollectionUnderstanding Java Garbage Collection
Understanding Java Garbage Collection
 
ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022ZIO-Direct - Functional Scala 2022
ZIO-Direct - Functional Scala 2022
 
Spark Workshop
Spark WorkshopSpark Workshop
Spark Workshop
 
Apache Flink internals
Apache Flink internalsApache Flink internals
Apache Flink internals
 
‘go-to’ general-purpose sequential collections - from Java To Scala
‘go-to’ general-purpose sequential collections -from Java To Scala‘go-to’ general-purpose sequential collections -from Java To Scala
‘go-to’ general-purpose sequential collections - from Java To Scala
 
scalar.pdf
scalar.pdfscalar.pdf
scalar.pdf
 
Sequence and Traverse - Part 1
Sequence and Traverse - Part 1Sequence and Traverse - Part 1
Sequence and Traverse - Part 1
 
Refactoring Functional Type Classes
Refactoring Functional Type ClassesRefactoring Functional Type Classes
Refactoring Functional Type Classes
 
Helm - Package manager in K8S
Helm - Package manager in K8SHelm - Package manager in K8S
Helm - Package manager in K8S
 
Arriving at monads by going from pure-function composition to effectful-funct...
Arriving at monads by going from pure-function composition to effectful-funct...Arriving at monads by going from pure-function composition to effectful-funct...
Arriving at monads by going from pure-function composition to effectful-funct...
 
Functional programming in Scala
Functional programming in ScalaFunctional programming in Scala
Functional programming in Scala
 
Presentación open closed principle
Presentación open closed principlePresentación open closed principle
Presentación open closed principle
 
Deep Dive into Spark
Deep Dive into SparkDeep Dive into Spark
Deep Dive into Spark
 

Similar to Modular programming Using Object in Scala

Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to javaSujit Majety
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...AnkurSingh340457
 
Ujjwalreverseengineeringppptfinal
UjjwalreverseengineeringppptfinalUjjwalreverseengineeringppptfinal
Ujjwalreverseengineeringppptfinalujjwalchauhan87
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to JavaSMIJava
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller ColumnsJonathan Fine
 
Example Of Import Java
Example Of Import JavaExample Of Import Java
Example Of Import JavaMelody Rios
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java LanguagePawanMM
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answersKrishnaov
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery PluginRavi Mone
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad NicheTech Com. Solutions Pvt. Ltd.
 

Similar to Modular programming Using Object in Scala (20)

Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Java notes jkuat it
Java notes jkuat itJava notes jkuat it
Java notes jkuat it
 
Java notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esectionJava notes(OOP) jkuat IT esection
Java notes(OOP) jkuat IT esection
 
Introduction to java
Introduction to javaIntroduction to java
Introduction to java
 
Java notes
Java notesJava notes
Java notes
 
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
FAL(2022-23)_CSE0206_ETH_AP2022232000455_Reference_Material_I_16-Aug-2022_Mod...
 
Ujjwalreverseengineeringppptfinal
UjjwalreverseengineeringppptfinalUjjwalreverseengineeringppptfinal
Ujjwalreverseengineeringppptfinal
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Ruby On Rails
Ruby On RailsRuby On Rails
Ruby On Rails
 
SMI - Introduction to Java
SMI - Introduction to JavaSMI - Introduction to Java
SMI - Introduction to Java
 
JavaScript Miller Columns
JavaScript Miller ColumnsJavaScript Miller Columns
JavaScript Miller Columns
 
JAVA-PPT'S.pdf
JAVA-PPT'S.pdfJAVA-PPT'S.pdf
JAVA-PPT'S.pdf
 
Example Of Import Java
Example Of Import JavaExample Of Import Java
Example Of Import Java
 
Java1
Java1Java1
Java1
 
Java
Java Java
Java
 
Session 02 - Elements of Java Language
Session 02 - Elements of Java LanguageSession 02 - Elements of Java Language
Session 02 - Elements of Java Language
 
Java interview questions and answers
Java interview questions and answersJava interview questions and answers
Java interview questions and answers
 
Jquery Plugin
Jquery PluginJquery Plugin
Jquery Plugin
 
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
Cocoa and MVC in ios, iOS Training Ahmedbad , iOS classes Ahmedabad
 

More from Knoldus 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.
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Knoldus Inc.
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxKnoldus Inc.
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinKnoldus Inc.
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks PresentationKnoldus Inc.
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Knoldus Inc.
 

More from Knoldus Inc. (20)

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
 
Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)Advanced Python (with dependency injection and hydra configuration packages)
Advanced Python (with dependency injection and hydra configuration packages)
 
Azure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptxAzure Databricks (For Data Analytics).pptx
Azure Databricks (For Data Analytics).pptx
 
The Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and KotlinThe Power of Dependency Injection with Dagger 2 and Kotlin
The Power of Dependency Injection with Dagger 2 and Kotlin
 
Data Engineering with Databricks Presentation
Data Engineering with Databricks PresentationData Engineering with Databricks Presentation
Data Engineering with Databricks Presentation
 
Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)Databricks for MLOps Presentation (AI/ML)
Databricks for MLOps Presentation (AI/ML)
 

Recently uploaded

FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | DelhiMalviyaNagarCallGirl
 
SHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 MagazineSHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 MagazineShivna Prakashan
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...akbard9823
 
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...akbard9823
 
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiMalviyaNagarCallGirl
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiMalviyaNagarCallGirl
 
Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMroute66connected
 
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiMalviyaNagarCallGirl
 
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...anilsa9823
 
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur DubaiBur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubaidajasot375
 
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiMalviyaNagarCallGirl
 
Jeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson
 
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | DelhiMalviyaNagarCallGirl
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...wdefrd
 
The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)thephillipta
 
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...gurkirankumar98700
 
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in DowntownDowntown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtowndajasot375
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...gurkirankumar98700
 
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...anilsa9823
 

Recently uploaded (20)

FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Old Rajendra Nagar | Delhi
 
SHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 MagazineSHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
SHIVNA SAHITYIKI APRIL JUNE 2024 Magazine
 
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
Hazratganj / Call Girl in Lucknow - Phone 🫗 8923113531 ☛ Escorts Service at 6...
 
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
Hazratganj ] (Call Girls) in Lucknow - 450+ Call Girl Cash Payment 🧄 89231135...
 
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in New Ashok Nagar | Delhi
 
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | DelhiFULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
FULL ENJOY - 9953040155 Call Girls in Indirapuram | Delhi
 
Roadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NMRoadrunner Lodge, Motel/Residence, Tucumcari NM
Roadrunner Lodge, Motel/Residence, Tucumcari NM
 
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Moti Nagar | Delhi
 
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
Lucknow 💋 Cheap Call Girls In Lucknow Finest Escorts Service 8923113531 Avail...
 
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur DubaiBur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
Bur Dubai Call Girls O58993O4O2 Call Girls in Bur Dubai
 
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | DelhiFULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
FULL ENJOY - 9953040155 Call Girls in Laxmi Nagar | Delhi
 
Jeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around EuropeJeremy Casson - An Architectural and Historical Journey Around Europe
Jeremy Casson - An Architectural and Historical Journey Around Europe
 
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | DelhiFULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
FULL ENJOY - 9953040155 Call Girls in Paschim Vihar | Delhi
 
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
Islamabad Escorts # 03080115551 # Escorts in Islamabad || Call Girls in Islam...
 
The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)The First Date by Daniel Johnson (Inspired By True Events)
The First Date by Daniel Johnson (Inspired By True Events)
 
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
Charbagh / best call girls in Lucknow - Book 🥤 8923113531 🪗 Call Girls Availa...
 
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in DowntownDowntown Call Girls O5O91O128O Pakistani Call Girls in Downtown
Downtown Call Girls O5O91O128O Pakistani Call Girls in Downtown
 
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...Gomti Nagar & High Profile Call Girls in Lucknow  (Adult Only) 8923113531 Esc...
Gomti Nagar & High Profile Call Girls in Lucknow (Adult Only) 8923113531 Esc...
 
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
Lucknow 💋 Escorts Service Lucknow Phone No 8923113531 Elite Escort Service Av...
 
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
Dxb Call Girls # +971529501107 # Call Girls In Dxb Dubai || (UAE)
 

Modular programming Using Object in Scala

  • 1.    Modular Programming  Using Object in Scala  Ruchi Jindal                                       Software Consultant    Knoldus
  • 2. Scala's Strength  Agile, with lightweight syntax  Scala is a pure object-oriented language  Functional Programming  Safe and performant, with strong static typing  Functions are objects  Everything is an object(Numbers are objects) 1 + 2 * 3 / x ====> (1).+(((2).*(3))./(x))
  • 3. Scala Says “If I were to pick a language to use today other than Java, it would be Scala.” - James Gosling, creator of Java “Scala, it must be stated, is the current heir apparent to the Java throne. No other language on the JVM seems as capable of being a "replacement for Java" as Scala, and the momentum behind Scala is now unquestionable. While Scala is not a dynamic language, it has many of the characteristics of popular dynamic languages, through its rich and flexible type system, its sparse and clean syntax, and its marriage of functional and object paradigms.” - Charles Nutter, creator of JRuby “I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.” - James Strachan, creator of Groovy.
  • 4. Why unify FP and OOP? Both have complementary strengths for composition: Functional programming: Object-oriented programming: Makes it easy to build interesting Makes it easy to adapt and extend things from simple parts, using complex systems, using • higher-order functions, • subtyping and inheritance, • algebraic types and • dynamic configurations, pattern matching, • classes as partial abstractions. • parametric polymorphism.
  • 5. Modular programming  Also known as top down design and stepwise refinement.  A software design technique that increases the extent to which software is composed of separate, interchangeable components called modules by breaking down program functions into modules, each of which accomplishes one function and contains everything necessary to accomplish this.  Conceptually, modules represent a separation of concerns, and improve maintainability by enforcing logical boundaries between components.  Modules are typically incorporated into the program through interfaces.
  • 6. Why Need Modular Approach Scala is a scalable language because we can use the same techniques to construct small as well as large programs. Programming in the large means organizing and assembling the smaller pieces into larger programs, applications, or systems. While the division of programs into packages is already quite helpful, it is limited because it provides no way to abstract. We cannot reconfigure a package two different ways within the same program, and you cannot inherit between packages. A package always includes one precise list of contents, and that list is fixed until you change the code. ................................
  • 7. Why we need Modular Approach....... Firstly there should be a module construct that provides a good separation of interface and implementation. Secondly, there should be a way to replace one module with another that has the same interface with out changing or recompiling the modules that depend on the replaced one. Lastly, there should be a way to wire modules together. This wiring task can by thought of as configuring the system.
  • 8. How To achieve Modular Approach  How to use Scala’s object-oriented features to make a program more modular  How a simple singleton object can be used as a module  How to use traits and classes as abstractions over modules. These abstractions can be reconfigured into multiple modules, even multiple times within the same program.  How to use traits to divide a module across multiple files
  • 9. To Build an enterprise web application you need the partition of the software into layers, including ➔ a domain layer ➔ an application layer In the domain layer, we define domain objects, which will capture business concepts and rules and encapsulate state that will be persisted to an external relational database. In the application layer, we’ll provide an API organized in terms of the services ,the application offers to clients (including the user interface layer). The application layer will implement these services by coordinating tasks and delegatingthe work to the objects of the domain layer.
  • 10. Lets Start with an Example An Enterprise web application that will allow users to manage recipes. It will contains two entities that will be persisted in the database. ➔ Food ➔ Recipe abstract class Food(val name: String) { override def toString = name } class Recipe(val name: String,val ingredients: List[Food],val instructions: String) { override def toString = name }
  • 11. Here are some singleton instances of Food and Recipe classes, which can be used when writing tests: object Apple extends Food("Apple") object Orange extends Food("Orange") object Cream extends Food("Cream") object Sugar extends Food("Sugar") object FruitSalad extends Recipe("fruit salad",List(Apple, Orange, Cream, Sugar),"Stir it all together.")
  • 12. Scala uses objects for modules, so to modularize program we are making two singleton objects to serve as the mock implementations of the database and browser modules during testing. object SimpleDatabase { def allFoods = List(Apple, Orange, Cream, Sugar) def foodNamed(name: String): Option[Food] = allFoods.find(_.name == name) def allRecipes: List[Recipe] = List(FruitSalad) } object SimpleBrowser { def recipesUsing(food: Food) = SimpleDatabase.allRecipes.filter(recipe => recipe.ingredients.contains(food)) }
  • 13. You can use this database and browser as follows: scala> val apple = SimpleDatabase.foodNamed("Apple").get apple: Food = Apple scala> SimpleBrowser.recipesUsing(apple) res0: List[Recipe] = List(fruit salad) To make things a little more interesting, suppose the database sorts foods into categories. To implement this, you can add a FoodCategory class and a list of all categories in the database. eg. class FoodCategory(name: String, foods: List[Food])
  • 14. object SimpleDatabase { def allFoods = List(Apple, Orange, Cream, Sugar) def foodNamed(name: String): Option[Food] = allFoods.find(_.name == name) def allRecipes: List[Recipe] = List(FruitSalad) case class FoodCategory(name: String, foods: List[Food]) private var categories = List( FoodCategory("fruits", List(Apple, Orange)), FoodCategory("misc", List(Cream, Sugar))) def allCategories = categories } object SimpleBrowser { def recipesUsing(food: Food) = SimpleDatabase.allRecipes.filter(recipe => recipe.ingredients.contains(food)) def displayCategory(category: SimpleDatabase.FoodCategory) { println(category) }}
  • 15. Abstraction The SimpleBrowser module mentions the SimpleDatabase mod- ule by name, you won’t be able to plug in a different implementation of the database module without modifying and recompiling the browser module. In addition, although there’s no hard link from the SimpleDatabase moduleto the SimpleBrowser module,there’s no clear way to enable the user interface layer, for example, to be configured to use different implementations of the browser module. abstract class Browser { val database: Database def recipesUsing(food: Food) = database.allRecipes.filter(recipe => recipe.ingredients.contains(food)) def displayCategory(category: database.FoodCategory) { println(category) } }
  • 16. abstract class Database { def allFoods: List[Food] def allRecipes: List[Recipe] def foodNamed(name: String) = allFoods.find(f => f.name == name) case class FoodCategory(name: String, foods: List[Food]) def allCategories: List[FoodCategory] } object SimpleDatabase extends Database { def allFoods = List(Apple, Orange, Cream, Sugar) def allRecipes: List[Recipe] = List(FruitSalad) private var categories = List( FoodCategory("fruits", List(Apple, Orange)), FoodCategory("misc", List(Cream, Sugar))) def allCategories = categories }
  • 17. object SimpleBrowser extends Browser { val database = SimpleDatabase } scala> val apple = SimpleDatabase.foodNamed("Apple").get apple: Food = Apple scala> SimpleBrowser.recipesUsing(apple) res1: List[Recipe] = List(fruit salad)
  • 18. Now we create a second mock database, and use the same browser class with it object StudentDatabase extends Database { object FrozenFood extends Food("FrozenFood") object HeatItUp extends Recipe( "heat it up", List(FrozenFood), "Microwave the 'food' for 10 minutes.") def allFoods = List(FrozenFood) def allRecipes = List(HeatItUp) def allCategories = List( FoodCategory("edible", List(FrozenFood))) } object StudentBrowser extends Browser { val database = StudentDatabase }
  • 19. Splitting modules into traits Often a module is too large to fit comfortably into a single file. When that happens, you can use traits to split a module into separate files. For example ,suppose you wanted to move categorization code out of the main Database file and into its own. trait FoodCategories { case class FoodCategory(name: String, foods: List[Food]) def allCategories: List[FoodCategory] } Now class Database can mix in the FoodCategories trait instead of defin- ing FoodCategory and allCategories itself abstract class Database extends FoodCategories { def allFoods: List[Food] def allRecipes: List[Recipe] def foodNamed(name: String) = allFoods.find(f => f.name == name) }
  • 20. Continuing in this way, you might try and divide SimpleDatabase into two traits, one for foods and one for recipes. object SimpleDatabase extends Database with SimpleFoods with SimpleRecipes The SimpleFoods trait could look as : trait SimpleFoods { object Pear extends Food("Pear") def allFoods = List(Apple, Pear) def allCategories = Nil }
  • 21. Runtime linking One final feature of Scala modules is worth emphasizing: they can be linked together at runtime, and you can decide which modules will link to which depending on runtime computations. object GotApples { def main(args: Array[String]) { val db: Database = if(args(0) == "student") StudentDatabase else SimpleDatabase object browser extends Browser { val database = db } val apple = SimpleDatabase.foodNamed("Apple").get for(recipe <- browser.recipesUsing(apple)) println(recipe) } }
  • 22. if you use the simple database, you will find a recipe for fruit salad. If you use the student database, you will find no recipes at all using apples: $ scala GotApples simple fruit salad $ scala GotApples student $//No output
  • 23. Tracking module instances Despite using the same code, the different browser and database modules cre- ated in the previous section really are separate modules. This means that each module has its own contents, including any nested classes. FoodCategory in SimpleDatabase, for example, is a different class from FoodCategory in StudentDatabase! scala> val category = StudentDatabase.allCategories.head category: StudentDatabase.FoodCategory = FoodCategory(edible,List(FrozenFood)) scala> SimpleBrowser.displayCategory(category) <console>:12: error: type mismatch; found : StudentDatabase.FoodCategory required: SimpleBrowser.database.FoodCategory SimpleBrowser.displayCategory(category) ˆ If we want all FoodCategorys to be the same, we can accomplish this by moving the definition of FoodCategory outside of any class or trait.