Skip to content
Snippets Groups Projects
Forked from an inaccessible project.

% Business Domain Modeling % %

Business Domain Modeling

Enums and case classes together provide basic building blocks for defining data types.

They are typically used to model the business domain of a program.

How to Model Things?

Modeling consists of translating concepts from the real world into data type definitions in the Scala world.

Modeling requires you to think about what details of the real world are relevant for your program.

The purpose of abstraction is not to be vague, but to create a new semantic level in which one can be absolutely precise.

Edsger W. Dijkstra

Modeling Methodology (1)

There is no systematic methodology: often, a same set of concepts can be modeled in multiple ways.

But here are some advice.

->

  • Identify the concepts (in general, nouns) that you are interested in
  • Identify the relations between them
    • Does a concept belong to another one?
      • e.g. “a rational number has a numerator and a denominator”
      • e.g. “a sum has a left summand and a right summand”
    • Does a concept generalize another one?
      • e.g. “‘functional programming’ is a possible programming paradigm”
      • e.g. “an arithmetic operation can either be a product or a sum”

Modeling Methodology (2)

  • Translate each concept into a type definition
    • Concepts belonging to others become fields of case classes or of enumeration cases
    • Concepts generalizing others become enumerations
  • Check that you can construct meaningful objects from your model

Example: Painting Application

An image is made of a shape, a stroke width and a color.

Possible shapes are a square or a circle. A square has a side length. A circle has a radius.

A color has a blue component, a red component and a green component. Each component of a color is an integer value (between 0 and 255).

->

case class Image(shape: Shape, strokeWidth: Int, color: Color)

enum Shape {
  case Square(side: Double)
  case Circle(radius: Double)
}

case class Color(red: Int, green: Int, blue: Int)

Example: Painting Application

case class Image(shape: Shape, strokeWidth: Int, color: Color)

enum Shape
  case Square(side: Double)
  case Circle(radius: Double)

case class Color(red: Int, green: Int, blue: Int)

A blue circle:

val blue = Color(0, 0, 255)
val blueCircle = Image(Circle(10), 1, blue)

Data Types Define a Space of Possible States

The domain model defines the rules for constructing objects representing a possible state of a program.

The more possible states, the more risks to have bugs or to reach illegal states.

Hint: restrict the space of possible states to the minimum.

Summary

In this lecture we have seen how to model the business domain of a program using enumerations and case classes.