SlideShare a Scribd company logo
1 of 94
Download to read offline
Functional and
Algebraic Domain
Modeling
Debasish Ghosh
@debasishg
Functional and
Algebraic Domain
Modeling
Debasish Ghosh
@debasishg
Functional Programming
ā€¢ programming with pure functions
ā€¢ a functionā€™s output is solely determined by the input
(much like mathematical functions)
ā€¢ no assignment, no side-effects
ā€¢(pure) mapping between values
ā€¢ functions compose
ā€¢ expression-oriented programming
Functional and
Algebraic Domain
Modeling
Debasish Ghosh
@debasishg
What is an Algebra ?
Algebra is the study of algebraic structures
InĀ mathematics, and more speciļ¬cally inĀ abstract
algebra, anĀ algebraic structureĀ is
aĀ setĀ (calledĀ carrier setĀ orĀ underlying set)
with one or moreĀ ļ¬nitary operationsĀ deļ¬ned on it
that satisļ¬es a list of axioms
-Wikipedia
(https://en.wikipedia.org/wiki/Algebraic_structure)
Set A
Ļ• : A Ɨ A ā†’ A
fo r (a, b) āˆˆ A
Ļ•(a, b)
a Ļ• b
given
a binary operation
for specific a, b
or
The Algebra of Sets
Algebraic Thinking
ā€¢ Thinking and reasoning about code in terms of the
data types and the operations they support
without considering a bit about the underlying
implementations
ā€¢ f: A => B and g: B => C, we should be able to
reason that we can compose f and g algebraically
to build a larger function h: A => C
ā€¢algebraic composition
Functional and
Algebraic Domain
Modeling
Debasish Ghosh
@debasishg
Domain Modeling
Domain Modeling
(Functional)
What is a domain model ?
A domain model in problem solving and software engineering is a
conceptual model of all the topics related to a speciļ¬c problem. It
describes the various entities, their attributes, roles, and
relationships, plus the constraints that govern the problem domain.
It does not describe the solutions to the problem.
Wikipedia (http://en.wikipedia.org/wiki/Domain_model)
https://msdn.microsoft.com/en-us/library/jj591560.aspx
A Bounded Context
ā€¢ has a consistent vocabulary
ā€¢ a set of domain behaviors modeled as
functions on domain objects
implemented as types
ā€¢ each of the behaviors honor a set of
business rules
ā€¢ related behaviors grouped as modules
Domain Model = āˆŖ(i) Bounded Context(i)
Bounded Context = { m[T1,T2,..] | T(i) āˆˆ Types }
Module = { f(x,y,..) | p(x,y) āˆˆ Domain Rules }
ā€¢ domain function
ā€¢ on an object of types x, y, ..
ā€¢ composes with other functions
ā€¢ closed under composition
ā€¢ business rules
ā€¢ Functions / Morphisms
ā€¢ Types / Sets
ā€¢ Composition
ā€¢ Rules / Laws
algebra
explicit veriļ¬able
ā€¢ types
ā€¢ type constraints
ā€¢ functions between types
ā€¢ type constraints
ā€¢ more constraints if you have DT
ā€¢ algebraic property based testing
(algebra of types, functions & laws
of the solution domain model)
Domain Model Algebra
What is meant by the
algebra of a type ?
ā€¢Nothing
ā€¢Unit
ā€¢Boolean
ā€¢Byte
ā€¢String
What is meant by the
algebra of a type ?
ā€¢Nothing -> 0
ā€¢Unit -> 1
ā€¢Boolean -> 2
ā€¢Byte -> 256
ā€¢String -> a lot
What is meant by the
algebra of a type ?
ā€¢(Boolean, Unit)
ā€¢(Byte, Unit)
ā€¢(Byte, Boolean)
ā€¢(Byte, Byte)
ā€¢(String, String)
What is meant by the
algebra of a type ?
ā€¢(Boolean, Unit) -> 2x1 = 2
ā€¢(Byte, Unit) -> 256x1 = 256
ā€¢(Byte, Boolean) -> 256x2 = 512
ā€¢(Byte, Byte) -> 256x256 = 65536
ā€¢(String, String) -> a lot
What is meant by the
algebra of a type ?
ā€¢ Quiz: Generically, how many inhabitants can we
have for a type (a, b)?
ā€¢ Answer: 1 inhabitant for each combination of
aā€™s and bā€™s (a x b)
Product Types
ā€¢ Ordered pairs of values one from each type in
the order speciļ¬ed - this and that
ā€¢ Can be generalized to a ļ¬nite product indexed by
a ļ¬nite set of indices
Product Types in Scala
type Point = (Int, Int)
val p = (10, 12)
case class Account(no: String,
name: String,
address: String,
dateOfOpening: Date,
dateOfClosing: Option[Date]
)
What is meant by the
algebra of a type ?
ā€¢Boolean or Unit
ā€¢Byte or Unit
ā€¢Byte or Boolean
ā€¢Byte or Byte
ā€¢String or String
What is meant by the
algebra of a type ?
ā€¢Boolean or Unit -> 2+1 = 3
ā€¢Byte or Unit -> 256+1 = 257
ā€¢Byte or Boolean -> 256+2 = 258
ā€¢Byte or Byte -> 256+256 = 512
ā€¢String or String -> a lot
Sum Types
ā€¢ Model data structures involving alternatives -
this or that
ā€¢ A tree can have a leaf or an internal node which,
is again a tree
ā€¢ In Scala, a sum type is usually referred to as an
Algebraic DataType (ADT)
Sum Types in Scala
sealed trait Shape
case class Circle(origin: Point,
radius: BigDecimal) extends Shape
case class Rectangle(diag_1: Point,
diag_2: Point) extends Shape
Sum Types are
Expressive
ā€¢ Booleans - true or false
ā€¢ Enumerations - sum types may be used to deļ¬ne ļ¬nite
enumeration types, whose values are one of an explicitly
speciļ¬ed ļ¬nite set
ā€¢ Optionality - the Option data type in Scala is encoded using a
sum type
ā€¢ Disjunction - this or that, the Either data type in Scala
ā€¢ Failure encoding - the Try data type in Scala to indicate that
the computation may raise an exception
sealed trait InstrumentType
case object CCY extends InstrumentType
case object EQ extends InstrumentType
case object FI extends InstrumentType
sealed trait Instrument {
def instrumentType: InstrumentType
}
case class Equity(isin: String, name: String, issueDate: Date,
faceValue: Amount) extends Instrument {
final val instrumentType = EQ
}
case class FixedIncome(isin: String, name: String, issueDate: Date,
maturityDate: Option[Date], nominal: Amount) extends Instrument {
final val instrumentType = FI
}
case class Currency(isin: String) extends Instrument {
final val instrumentType = CCY
}
De-structuring with
Pattern Matching
def process(i: Instrument) = i match {
case Equity(isin, _, _, faceValue) => // ..
case FixedIncome(isin, _, issueDate, _, nominal) => // ..
case Currency(isin) => // ..
}
Exhaustiveness Check
Sum Types and Domain
Models
ā€¢ Models heterogeneity and heterogenous data
structures are ubiquitous in a domain model
ā€¢ Allows modeling of expressive domain types in a
succinct and secure way - secure by construction
ā€¢ Pattern matching makes encoding domain logic
easy and expressive
ā€“ Robert Harper in Practical Foundations of Programming Languages
ā€œThe absence of sums is the origin of C. A. R.
Hoareā€™s self-described ā€˜billion dollar mistake,ā€™
the null pointerā€
More algebra of types
ā€¢ Exponentiation - f: A => B has b^a
inhabitants
ā€¢ Taylor Series - Recursive Data Types
ā€¢ Derivatives - Zippers
ā€¢ ā€¦
Scaling of the Algebra
ā€¢ Since a function is a mapping from the domain of types
to the co-domain of types, we can talk about the
algebra of a function
ā€¢ A module is a collection of related functions - we can
think of the algebra of a module as the union of
the algebras of all functions that it encodes
ā€¢ A domain model (one bounded context) can be loosely
thought of as a collection of modules, which gives rise
to the connotation of a domain model algebra
Algebraic Composition
ā€¢ Functions compose based on types, which
means ..
ā€¢ Algebras compose
ā€¢ Giving rise to larger algebras / functions, which
in turn implies ..
ā€¢ We can construct larger domain behaviors by
composing smaller behaviors
Algebras are Ubiquitous
ā€¢ Generic, parametric and hence usable on an
inļ¬nite set of data types, including your domain
modelā€™s types
Algebras are Ubiquitous
ā€¢ Generic, parametric and hence usable on an
inļ¬nite set of data types, including your domain
modelā€™s types
ā€¢ Clear separation between the contract (the
algebra) and its implementations
(interpreters)
Algebras are Ubiquitous
ā€¢ Generic, parametric and hence usable on an
inļ¬nite set of data types, including your domain
modelā€™s types
ā€¢ Clear separation between the contract (the
algebra) and its implementations
(interpreters)
ā€¢ Standard vocabulary (like design patterns)
Algebras are Ubiquitous
ā€¢ Generic, parametric and hence usable on an
inļ¬nite set of data types, including your domain
modelā€™s types
ā€¢ Clear separation between the contract (the
algebra) and its implementations (interpreters)
ā€¢ Standard vocabulary (like design patterns)
ā€¢ Existing set of reusable algebras offered by the
standard libraries
Roadmap to a Functional
and Algebraic Model
1. Identify domain behaviors
2. Identify the algebras of functions (not implementation)
3. Compose algebras to form larger behaviors - follow
the types depending on the semantics of
compositionality.We call this behavior a program that
models the use case
4. Plug in concrete types to complete the
implementation
Domain Model = āˆŖ(i) Bounded Context(i)
Bounded Context = { m[T1,T2,..] | T(i) āˆˆ Types }
Module = { f(x,y,..) | p(x,y) āˆˆ Domain Rules }
ā€¢ domain function
ā€¢ on an object of types x, y
ā€¢ composes with other functions
ā€¢ closed under composition
ā€¢ business rules
Domain Model = āˆŖ(i) Bounded Context(i)
Bounded Context = { m[T1,T2,..] | T(i) āˆˆ Types }
Module = { f(x,y,..) | p(x,y) āˆˆ Domain Rules }
ā€¢ domain function
ā€¢ on an object of types x, y
ā€¢ composes with other functions
ā€¢ closed under composition
ā€¢ business rules
Domain Algebra
Domain Algebra
Given all the properties of algebra, can we
consider algebraic composition to be the
basis of designing, implementing and modularizing
domain models ?
Client places order
- ļ¬‚exible format
1
Client places order
- ļ¬‚exible format
Transform to internal domain
model entity and place for execution
1 2
Client places order
- ļ¬‚exible format
Transform to internal domain
model entity and place for execution
Trade & Allocate to
client accounts
1 2
3
def fromClientOrder: ClientOrder => Order
def execute(market: Market, brokerAccount: Account)
: Order => List[Execution]
def allocate(accounts: List[Account])
: List[Execution] => List[Trade]
trait Trading {
}
trait TradeComponent extends Trading
with Logging with Auditing
algebra of domain
behaviors / functions
functions aggregate
upwards into modules
modules aggregate
into larger modules
.. so we have a decent algebra of our module, the
names reļ¬‚ect the appropriate artifacts from the
domain (ubiquitous language), the types are
well published and we are quite explicit in what
the behaviors do ..
1. Compositionality - How do we compose
the 3 behaviors that we published to
generate trade in the market and allocate
to client accounts ?
2. Side-effects - We need to compose them
alongside all side-effects that form a core
part of all non trivial domain model
implementations
ā€¢ Error handling ?
ā€¢ throw / catch exceptions is not RT
ā€¢ Partiality ?
ā€¢ partial functions can report runtime exceptions if invoked
with unhandled arguments (violates RT)
ā€¢ Reading conļ¬guration information from environment ?
ā€¢ may result in code repetition if not properly handled
ā€¢ Logging ?
ā€¢ side-effects
Side-effects
Side-effects
ā€¢ Database writes
ā€¢ Writing to a message queue
ā€¢ Reading from stdin / ļ¬les
ā€¢ Interacting with any external resource
ā€¢ Changing state in place
modularity
side-effects donā€™t compose
.. the semantics of compositionality ..
in the presence of side-effects
Algebra to the rescue ..
Algebra to the rescue ..
of types
Abstract side-effects into
data type constructors
Abstract side-effects into
data type constructors,
which we call Effects ..
Option[A]
Either[A,B]
(partiality)
(disjunction)
List[A]
(non-determinism)
Reader[E,A]
(read from environment aka dependency Injection)
Writer[W,A]
(logging)
State[S,A]
(state management)
IO[A]
(external side-effects)
.. and there are many many more ..
F[A]
The answer that the
effect computesThe additional stuff
modeling the computation
ā€¢ The F[_] that we saw is an opaque type - it
has no denotation till we give it one
ā€¢ The denotation that we give to F[_] depends
on the semantics of compositionality that we
would like to have for our domain model
behaviors
def fromClientOrder: ClientOrder => F[Order]
def execute(market: Market, brokerAccount: Account)
: Order => F[List[Execution]]
def allocate(accounts: List[Account])
: List[Execution] => F[List[Trade]]
trait Trading[F[_]] {
}
Effect Type
ā€¢ Just the Algebra

ā€¢ No denotation, no
concrete type

ā€¢ Explicitly stating that we
have eļ¬€ectful functions
here
def fromClientOrder: ClientOrder => F[Order]
def execute(market: Market, brokerAccount: Account)
: Order => F[List[Execution]]
def allocate(accounts: List[Account])
: List[Execution] => F[List[Trade]]
trait Trading[F[_]] {
}
Effect Type
ā€¢ .. we have intentionally kept the algebra open
for interpretation ..
ā€¢ .. there are use cases where you would like to
have multiple interpreters for the same
algebra ..
The Program
def tradeGeneration[M[_]: Monad](T: Trading[M]) = for {
order <- T.fromClientOrder(cor)
executions <- T.execute(m1, ba, order)
trades <- T.allocate(List(ca1, ca2, ca3), executions)
} yield trades
class TradingInterpreter[F[_]]
(implicit me: MonadError[F, Throwable])
extends Trading[F] {
def fromClientOrder: ClientOrder => F[Order] = makeOrder(_) match {
case Left(dv) => me.raiseError(new Exception(dv.message))
case Right(o) => o.pure[F]
}
def execute(market: Market, brokerAccount: Account)
: Order => F[List[Execution]] = ...
def allocate(accounts: List[Account])
: List[Execution] => F[List[Trade]] = ...
}
One Sample Interpreter
ā€¢ .. one lesson in modularity - commit to a
concrete implementation as late as
possible in the design ..
ā€¢ .. we have just indicated that we want a
monadic effect - we havenā€™t committed to
any concrete monad type even in the
interpreter ..
The Program
def tradeGeneration[M[_]: Monad](T: Trading[M]) = for {
order <- T.fromClientOrder(cor)
executions <- T.execute(m1, ba, order)
trades <- T.allocate(List(ca1, ca2, ca3), executions)
} yield trades
import cats.effect.IO
object TradingComponent extends TradingInterpreter[IO]
tradeGeneration(TradingComponent).unsafeRunSync
The Program
def tradeGeneration[M[_]: Monad](T: Trading[M]) = for {
order <- T.fromClientOrder(cor)
executions <- T.execute(m1, ba, order)
trades <- T.allocate(List(ca1, ca2, ca3), executions)
} yield trades
import monix.eval.Task
object TradingComponent extends TradingInterpreter[Task]
tradeGeneration(TradingComponent)
The Program
def tradeGenerationLoggable[M[_]: Monad]
(T: Trading[M], L: Logging[M]) = for {
_ <- L.info("starting order processing")
order <- T.fromClientOrder(cor)
executions <- T.execute(m1, ba, order)
trades <- T.allocate(List(ca1, ca2, ca3), executions)
_ <- L.info("allocation done")
} yield trades
object TradingComponent extends TradingInterpreter[IO]
object LoggingComponent extends LoggingInterpreter[IO]
tradeGenerationLoggable(TradingComponent, LoggingComponent).unsafeRunSync
Raise the level of
abstraction
trait Trading[F[_]] {
def fromClientOrder
: Kleisli[F, ClientOrder, Order]
def execute(market: Market, brokerAccount: Account)
: Kleisli[F, Order, List[Execution]]
def allocate(accounts: List[Account])
: Kleisli[F, List[Execution], List[Trade]]
}
The Program
def tradeGeneration[M[_]: Monad](T: Trading[M])
: Kleisli[M, ClientOrder, List[Trade]] = {
T.fromClientOrder andThen
T.execute(m1, ba) andThen
T.allocate(List(ca1, ca2, ca3))
}
object TradingComponent extends TradingInterpreter[IO]
val tk = tradeGeneration(TradingComponent)
tk(cor).unsafeRunSync
Effects
Side-effects
- Rob Norris at scale.bythebay.io talk - 2017 (https://www.youtube.com/
watch?v=po3wmq4S15A)
ā€œEffects and side-effects are not the same thing. Effects are
good, side-effects are bugs.Their lexical similarity is really
unfortunate because people often conļ¬‚ate the two ideasā€
Takeaways
ā€¢ Algebra scales from that of one single data type to
an entire bounded context
ā€¢ Algebras compose enabling composition of
domain behaviors
ā€¢ Algebras let you focus on the compositionality
without any context of implementation
ā€¢ Statically typed functional programming is
programming with algebras
Takeaways
ā€¢ Abstract early, interpret as late as possible
ā€¢ Abstractions / functions compose only when they are
abstract and parametric
ā€¢ Modularity in the presence of side-effects is a challenge
ā€¢ Effects as algebras are pure values that can compose based
on laws
ā€¢ Honor the law of using the least powerful abstraction
that works
From the Bible
ā€œName classes and operations to describe their effect and purpose,
without reference to the means by which they do what they
promise.This relieves the client developer of the need to understand
the internals.These names should conform to the UBIQUITOUS
LANGUAGE so that team members can quickly infer their meaning.
Write a test for a behavior before creating it, to force your thinking
into client developer mode.ā€
- Eric Evans (Domain Driven Design)
in the chapter on Supple Design, while discussing
Intention Revealing Interfaces
ā€¢ All names are from the domain vocabulary

ā€¢ Just the algebra describing the promise, no
implementation details

ā€¢ Purpose and eļ¬€ect explicit - yes, literally
explicit with eļ¬€ects
def fromClientOrder: ClientOrder => F[Order]
def execute(market: Market, brokerAccount: Account)
: Order => F[List[Execution]]
def allocate(accounts: List[Account])
: List[Execution] => F[List[Trade]]
trait Trading[F[_]] {
}
From the Bible
ā€œPlace as much of the logic of the program as possible into
functions, operations that return results with no observable side-
effects.ā€
- Eric Evans (Domain Driven Design)
in the chapter on Supple Design, while discussing
Side-Eļ¬€ect-Free Functions
def tradeGeneration[M[_]: Monad](T: Trading[M]) = for {
order <- T.fromClientOrder(cor)
executions <- T.execute(m1, ba, order)
trades <- T.allocate(List(ca1, ca2, ca3), executions)
} yield trades
ā€¢ The program tradeGeneration is completely side-eļ¬€ect free. It
generates a pure value.

ā€¢ Since the program is pure, you can interpret it in many ways (as we saw
earlier).

ā€¢ The side-eļ¬€ects occur only when you submit the program to the run time
system.

ā€¢ This is also an example where using algebraic & functional approach we
get a clear separation between the building of an abstraction and
executing it.
From the Bible
ā€œWhen it ļ¬ts, deļ¬ne an operation whose return type is the same as
the type of its argument(s). If the implementer has state that is
used in the computation, then the implementer is effectively an
argument of the operation, so the argument(s) and return value
should be of the same type as the implementer. Such an operation
is closed under the set of instances of that type.A closed operation
provides a high-level interface without introducing any dependency
on other concepts.ā€
- Eric Evans (Domain Driven Design)
in the chapter on Supple Design, while discussing
Closure of Operations
trait Semigroup[A] {
def combine(x: A, y: A): A
}
trait Monoid[A] extends Semigroup[A] {
def empty: A
}
ā€¢ With algebraic modeling, you can encode the closure of operations
through the algebra of a Monoid.

ā˜… parametric

ā˜… deļ¬ne the algebra once, implement it as many times based on the
context

ā˜… compositionality at the algebra level

ā€¢ For stateful computation, use the algebra of the State Monad and
manipulate state as a Monoid
Questions?

More Related Content

What's hot

Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Scott Wlaschin
Ā 
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
Ā 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and FunctionsJussi Pohjolainen
Ā 
Design patterns
Design patternsDesign patterns
Design patternsabhisheksagi
Ā 
SonarQube for AEM
SonarQube for AEMSonarQube for AEM
SonarQube for AEMconnectwebex
Ā 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Philip Schwarz
Ā 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design PatternsLilia Sfaxi
Ā 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHPTaha Malampatti
Ā 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
Ā 
sets and maps
 sets and maps sets and maps
sets and mapsRajkattamuri
Ā 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Kamlesh Makvana
Ā 
Cohesion et couplage
Cohesion et couplage Cohesion et couplage
Cohesion et couplage Ahmed HARRAK
Ā 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVAAbhilash Nair
Ā 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
Ā 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentationRana Muhammad Asif
Ā 

What's hot (20)

Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)Domain Modeling with FP (DDD Europe 2020)
Domain Modeling with FP (DDD Europe 2020)
Ā 
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...
Ā 
Sax parser
Sax parserSax parser
Sax parser
Ā 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Ā 
Design patterns
Design patternsDesign patterns
Design patterns
Ā 
SonarQube for AEM
SonarQube for AEMSonarQube for AEM
SonarQube for AEM
Ā 
Inner class
Inner classInner class
Inner class
Ā 
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Scala 3 by Example - Algebraic Data Types for Domain Driven Design - Part 1
Ā 
Javascript Design Patterns
Javascript Design PatternsJavascript Design Patterns
Javascript Design Patterns
Ā 
XSLT presentation
XSLT presentationXSLT presentation
XSLT presentation
Ā 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Ā 
Java exception handling
Java exception handlingJava exception handling
Java exception handling
Ā 
TypeScript Presentation
TypeScript PresentationTypeScript Presentation
TypeScript Presentation
Ā 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Ā 
sets and maps
 sets and maps sets and maps
sets and maps
Ā 
Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function Virtual function in C++ Pure Virtual Function
Virtual function in C++ Pure Virtual Function
Ā 
Cohesion et couplage
Cohesion et couplage Cohesion et couplage
Cohesion et couplage
Ā 
Classes, objects in JAVA
Classes, objects in JAVAClasses, objects in JAVA
Classes, objects in JAVA
Ā 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
Ā 
Design pattern-presentation
Design pattern-presentationDesign pattern-presentation
Design pattern-presentation
Ā 

Similar to Functional and Algebraic Domain Modeling

Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed worldDebasish Ghosh
Ā 
An Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain ModelingAn Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain ModelingDebasish Ghosh
Ā 
Architectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsArchitectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsDebasish Ghosh
Ā 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxMarco Parenzan
Ā 
Programming in python
Programming in pythonProgramming in python
Programming in pythonIvan Rojas
Ā 
Mining Functional Patterns
Mining Functional PatternsMining Functional Patterns
Mining Functional PatternsDebasish Ghosh
Ā 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netwww.myassignmenthelp.net
Ā 
Algebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsDebasish Ghosh
Ā 
Data Structures - Lecture 1 - Unit 1.pptx
Data Structures  - Lecture 1 - Unit 1.pptxData Structures  - Lecture 1 - Unit 1.pptx
Data Structures - Lecture 1 - Unit 1.pptxDanielNesaKumarC
Ā 
OODIAGRAMS (4).ppt
OODIAGRAMS (4).pptOODIAGRAMS (4).ppt
OODIAGRAMS (4).pptBalasundaramSr
Ā 
Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...
Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...
Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...Francesco Cauteruccio
Ā 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos3Pillar Global
Ā 
Linq Introduction
Linq IntroductionLinq Introduction
Linq IntroductionNeeraj Kaushik
Ā 

Similar to Functional and Algebraic Domain Modeling (20)

Power of functions in a typed world
Power of functions in a typed worldPower of functions in a typed world
Power of functions in a typed world
Ā 
An Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain ModelingAn Algebraic Approach to Functional Domain Modeling
An Algebraic Approach to Functional Domain Modeling
Ā 
Architectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain ModelsArchitectural Patterns in Building Modular Domain Models
Architectural Patterns in Building Modular Domain Models
Ā 
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptxStatic abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Static abstract members nelle interfacce di C# 11 e dintorni di .NET 7.pptx
Ā 
Programming in python
Programming in pythonProgramming in python
Programming in python
Ā 
Mining Functional Patterns
Mining Functional PatternsMining Functional Patterns
Mining Functional Patterns
Ā 
34. uml
34. uml34. uml
34. uml
Ā 
Learn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.netLearn ActionScript programming myassignmenthelp.net
Learn ActionScript programming myassignmenthelp.net
Ā 
Algebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain ModelsAlgebraic Thinking for Evolution of Pure Functional Domain Models
Algebraic Thinking for Evolution of Pure Functional Domain Models
Ā 
Data Structures - Lecture 1 - Unit 1.pptx
Data Structures  - Lecture 1 - Unit 1.pptxData Structures  - Lecture 1 - Unit 1.pptx
Data Structures - Lecture 1 - Unit 1.pptx
Ā 
OODIAGRAMS (4).ppt
OODIAGRAMS (4).pptOODIAGRAMS (4).ppt
OODIAGRAMS (4).ppt
Ā 
OODIAGRAMS.ppt
OODIAGRAMS.pptOODIAGRAMS.ppt
OODIAGRAMS.ppt
Ā 
OODIAGRAMS.ppt
OODIAGRAMS.pptOODIAGRAMS.ppt
OODIAGRAMS.ppt
Ā 
Aspdot
AspdotAspdot
Aspdot
Ā 
2CPP16 - STL
2CPP16 - STL2CPP16 - STL
2CPP16 - STL
Ā 
Functions
FunctionsFunctions
Functions
Ā 
Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...
Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...
Extending High-Utility Pattern Mining with Facets and Advanced Utility Functi...
Ā 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Ā 
Linq Introduction
Linq IntroductionLinq Introduction
Linq Introduction
Ā 
c++ Unit III - PPT.pptx
c++ Unit III - PPT.pptxc++ Unit III - PPT.pptx
c++ Unit III - PPT.pptx
Ā 

More from Debasish Ghosh

Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsDebasish Ghosh
Ā 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingDebasish Ghosh
Ā 
From functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modelingFrom functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modelingDebasish Ghosh
Ā 
Domain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approachDomain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approachDebasish Ghosh
Ā 
Functional Patterns in Domain Modeling
Functional Patterns in Domain ModelingFunctional Patterns in Domain Modeling
Functional Patterns in Domain ModelingDebasish Ghosh
Ā 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesDebasish Ghosh
Ā 
Big Data - architectural concerns for the new age
Big Data - architectural concerns for the new ageBig Data - architectural concerns for the new age
Big Data - architectural concerns for the new ageDebasish Ghosh
Ā 
DSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic modelDSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic modelDebasish Ghosh
Ā 
Dependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDebasish Ghosh
Ā 

More from Debasish Ghosh (9)

Approximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming ApplicationsApproximation Data Structures for Streaming Applications
Approximation Data Structures for Streaming Applications
Ā 
Functional and Algebraic Domain Modeling
Functional and Algebraic Domain ModelingFunctional and Algebraic Domain Modeling
Functional and Algebraic Domain Modeling
Ā 
From functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modelingFrom functional to Reactive - patterns in domain modeling
From functional to Reactive - patterns in domain modeling
Ā 
Domain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approachDomain Modeling with Functions - an algebraic approach
Domain Modeling with Functions - an algebraic approach
Ā 
Functional Patterns in Domain Modeling
Functional Patterns in Domain ModelingFunctional Patterns in Domain Modeling
Functional Patterns in Domain Modeling
Ā 
Property based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rulesProperty based Testing - generative data & executable domain rules
Property based Testing - generative data & executable domain rules
Ā 
Big Data - architectural concerns for the new age
Big Data - architectural concerns for the new ageBig Data - architectural concerns for the new age
Big Data - architectural concerns for the new age
Ā 
DSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic modelDSL - expressive syntax on top of a clean semantic model
DSL - expressive syntax on top of a clean semantic model
Ā 
Dependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake PatternDependency Injection in Scala - Beyond the Cake Pattern
Dependency Injection in Scala - Beyond the Cake Pattern
Ā 

Recently uploaded

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
Ā 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Hr365.us smith
Ā 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
Ā 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
Ā 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
Ā 
č‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1制作
č‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1åˆ¶ä½œč‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1制作
č‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1制作qr0udbr0
Ā 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf31events.com
Ā 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
Ā 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
Ā 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
Ā 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
Ā 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
Ā 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
Ā 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
Ā 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...OnePlan Solutions
Ā 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
Ā 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
Ā 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Natan Silnitsky
Ā 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceBrainSell Technologies
Ā 

Recently uploaded (20)

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
Ā 
Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)Recruitment Management Software Benefits (Infographic)
Recruitment Management Software Benefits (Infographic)
Ā 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Ā 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Ā 
Hot Sexy call girls in Patel NagaršŸ” 9953056974 šŸ” escort Service
Hot Sexy call girls in Patel NagaršŸ” 9953056974 šŸ” escort ServiceHot Sexy call girls in Patel NagaršŸ” 9953056974 šŸ” escort Service
Hot Sexy call girls in Patel NagaršŸ” 9953056974 šŸ” escort Service
Ā 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
Ā 
č‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1制作
č‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1åˆ¶ä½œč‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1制作
č‹±å›½UN学位čƁ,åŒ—å®‰ę™®é”æ大学ęƕäøščƁ书1:1制作
Ā 
Sending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdfSending Calendar Invites on SES and Calendarsnack.pdf
Sending Calendar Invites on SES and Calendarsnack.pdf
Ā 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
Ā 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
Ā 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
Ā 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Ā 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
Ā 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
Ā 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
Ā 
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Tech Tuesday - Mastering Time Management Unlock the Power of OnePlan's Timesh...
Ā 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
Ā 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
Ā 
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Taming Distributed Systems: Key Insights from Wix's Large-Scale Experience - ...
Ā 
CRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. SalesforceCRM Contender Series: HubSpot vs. Salesforce
CRM Contender Series: HubSpot vs. Salesforce
Ā 

Functional and Algebraic Domain Modeling

  • 3. Functional Programming ā€¢ programming with pure functions ā€¢ a functionā€™s output is solely determined by the input (much like mathematical functions) ā€¢ no assignment, no side-effects ā€¢(pure) mapping between values ā€¢ functions compose ā€¢ expression-oriented programming
  • 4.
  • 5.
  • 7. What is an Algebra ? Algebra is the study of algebraic structures InĀ mathematics, and more speciļ¬cally inĀ abstract algebra, anĀ algebraic structureĀ is aĀ setĀ (calledĀ carrier setĀ orĀ underlying set) with one or moreĀ ļ¬nitary operationsĀ deļ¬ned on it that satisļ¬es a list of axioms -Wikipedia (https://en.wikipedia.org/wiki/Algebraic_structure)
  • 8. Set A Ļ• : A Ɨ A ā†’ A fo r (a, b) āˆˆ A Ļ•(a, b) a Ļ• b given a binary operation for specific a, b or The Algebra of Sets
  • 9. Algebraic Thinking ā€¢ Thinking and reasoning about code in terms of the data types and the operations they support without considering a bit about the underlying implementations ā€¢ f: A => B and g: B => C, we should be able to reason that we can compose f and g algebraically to build a larger function h: A => C ā€¢algebraic composition
  • 13. What is a domain model ? A domain model in problem solving and software engineering is a conceptual model of all the topics related to a speciļ¬c problem. It describes the various entities, their attributes, roles, and relationships, plus the constraints that govern the problem domain. It does not describe the solutions to the problem. Wikipedia (http://en.wikipedia.org/wiki/Domain_model)
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 20. A Bounded Context ā€¢ has a consistent vocabulary ā€¢ a set of domain behaviors modeled as functions on domain objects implemented as types ā€¢ each of the behaviors honor a set of business rules ā€¢ related behaviors grouped as modules
  • 21. Domain Model = āˆŖ(i) Bounded Context(i) Bounded Context = { m[T1,T2,..] | T(i) āˆˆ Types } Module = { f(x,y,..) | p(x,y) āˆˆ Domain Rules } ā€¢ domain function ā€¢ on an object of types x, y, .. ā€¢ composes with other functions ā€¢ closed under composition ā€¢ business rules
  • 22. ā€¢ Functions / Morphisms ā€¢ Types / Sets ā€¢ Composition ā€¢ Rules / Laws algebra
  • 23. explicit veriļ¬able ā€¢ types ā€¢ type constraints ā€¢ functions between types ā€¢ type constraints ā€¢ more constraints if you have DT ā€¢ algebraic property based testing (algebra of types, functions & laws of the solution domain model) Domain Model Algebra
  • 24. What is meant by the algebra of a type ? ā€¢Nothing ā€¢Unit ā€¢Boolean ā€¢Byte ā€¢String
  • 25. What is meant by the algebra of a type ? ā€¢Nothing -> 0 ā€¢Unit -> 1 ā€¢Boolean -> 2 ā€¢Byte -> 256 ā€¢String -> a lot
  • 26. What is meant by the algebra of a type ? ā€¢(Boolean, Unit) ā€¢(Byte, Unit) ā€¢(Byte, Boolean) ā€¢(Byte, Byte) ā€¢(String, String)
  • 27. What is meant by the algebra of a type ? ā€¢(Boolean, Unit) -> 2x1 = 2 ā€¢(Byte, Unit) -> 256x1 = 256 ā€¢(Byte, Boolean) -> 256x2 = 512 ā€¢(Byte, Byte) -> 256x256 = 65536 ā€¢(String, String) -> a lot
  • 28. What is meant by the algebra of a type ? ā€¢ Quiz: Generically, how many inhabitants can we have for a type (a, b)? ā€¢ Answer: 1 inhabitant for each combination of aā€™s and bā€™s (a x b)
  • 29. Product Types ā€¢ Ordered pairs of values one from each type in the order speciļ¬ed - this and that ā€¢ Can be generalized to a ļ¬nite product indexed by a ļ¬nite set of indices
  • 30. Product Types in Scala type Point = (Int, Int) val p = (10, 12) case class Account(no: String, name: String, address: String, dateOfOpening: Date, dateOfClosing: Option[Date] )
  • 31. What is meant by the algebra of a type ? ā€¢Boolean or Unit ā€¢Byte or Unit ā€¢Byte or Boolean ā€¢Byte or Byte ā€¢String or String
  • 32. What is meant by the algebra of a type ? ā€¢Boolean or Unit -> 2+1 = 3 ā€¢Byte or Unit -> 256+1 = 257 ā€¢Byte or Boolean -> 256+2 = 258 ā€¢Byte or Byte -> 256+256 = 512 ā€¢String or String -> a lot
  • 33. Sum Types ā€¢ Model data structures involving alternatives - this or that ā€¢ A tree can have a leaf or an internal node which, is again a tree ā€¢ In Scala, a sum type is usually referred to as an Algebraic DataType (ADT)
  • 34. Sum Types in Scala sealed trait Shape case class Circle(origin: Point, radius: BigDecimal) extends Shape case class Rectangle(diag_1: Point, diag_2: Point) extends Shape
  • 35. Sum Types are Expressive ā€¢ Booleans - true or false ā€¢ Enumerations - sum types may be used to deļ¬ne ļ¬nite enumeration types, whose values are one of an explicitly speciļ¬ed ļ¬nite set ā€¢ Optionality - the Option data type in Scala is encoded using a sum type ā€¢ Disjunction - this or that, the Either data type in Scala ā€¢ Failure encoding - the Try data type in Scala to indicate that the computation may raise an exception
  • 36. sealed trait InstrumentType case object CCY extends InstrumentType case object EQ extends InstrumentType case object FI extends InstrumentType sealed trait Instrument { def instrumentType: InstrumentType } case class Equity(isin: String, name: String, issueDate: Date, faceValue: Amount) extends Instrument { final val instrumentType = EQ } case class FixedIncome(isin: String, name: String, issueDate: Date, maturityDate: Option[Date], nominal: Amount) extends Instrument { final val instrumentType = FI } case class Currency(isin: String) extends Instrument { final val instrumentType = CCY }
  • 37. De-structuring with Pattern Matching def process(i: Instrument) = i match { case Equity(isin, _, _, faceValue) => // .. case FixedIncome(isin, _, issueDate, _, nominal) => // .. case Currency(isin) => // .. }
  • 39. Sum Types and Domain Models ā€¢ Models heterogeneity and heterogenous data structures are ubiquitous in a domain model ā€¢ Allows modeling of expressive domain types in a succinct and secure way - secure by construction ā€¢ Pattern matching makes encoding domain logic easy and expressive
  • 40. ā€“ Robert Harper in Practical Foundations of Programming Languages ā€œThe absence of sums is the origin of C. A. R. Hoareā€™s self-described ā€˜billion dollar mistake,ā€™ the null pointerā€
  • 41. More algebra of types ā€¢ Exponentiation - f: A => B has b^a inhabitants ā€¢ Taylor Series - Recursive Data Types ā€¢ Derivatives - Zippers ā€¢ ā€¦
  • 42. Scaling of the Algebra ā€¢ Since a function is a mapping from the domain of types to the co-domain of types, we can talk about the algebra of a function ā€¢ A module is a collection of related functions - we can think of the algebra of a module as the union of the algebras of all functions that it encodes ā€¢ A domain model (one bounded context) can be loosely thought of as a collection of modules, which gives rise to the connotation of a domain model algebra
  • 43. Algebraic Composition ā€¢ Functions compose based on types, which means .. ā€¢ Algebras compose ā€¢ Giving rise to larger algebras / functions, which in turn implies .. ā€¢ We can construct larger domain behaviors by composing smaller behaviors
  • 44. Algebras are Ubiquitous ā€¢ Generic, parametric and hence usable on an inļ¬nite set of data types, including your domain modelā€™s types
  • 45. Algebras are Ubiquitous ā€¢ Generic, parametric and hence usable on an inļ¬nite set of data types, including your domain modelā€™s types ā€¢ Clear separation between the contract (the algebra) and its implementations (interpreters)
  • 46. Algebras are Ubiquitous ā€¢ Generic, parametric and hence usable on an inļ¬nite set of data types, including your domain modelā€™s types ā€¢ Clear separation between the contract (the algebra) and its implementations (interpreters) ā€¢ Standard vocabulary (like design patterns)
  • 47. Algebras are Ubiquitous ā€¢ Generic, parametric and hence usable on an inļ¬nite set of data types, including your domain modelā€™s types ā€¢ Clear separation between the contract (the algebra) and its implementations (interpreters) ā€¢ Standard vocabulary (like design patterns) ā€¢ Existing set of reusable algebras offered by the standard libraries
  • 48. Roadmap to a Functional and Algebraic Model 1. Identify domain behaviors 2. Identify the algebras of functions (not implementation) 3. Compose algebras to form larger behaviors - follow the types depending on the semantics of compositionality.We call this behavior a program that models the use case 4. Plug in concrete types to complete the implementation
  • 49. Domain Model = āˆŖ(i) Bounded Context(i) Bounded Context = { m[T1,T2,..] | T(i) āˆˆ Types } Module = { f(x,y,..) | p(x,y) āˆˆ Domain Rules } ā€¢ domain function ā€¢ on an object of types x, y ā€¢ composes with other functions ā€¢ closed under composition ā€¢ business rules
  • 50. Domain Model = āˆŖ(i) Bounded Context(i) Bounded Context = { m[T1,T2,..] | T(i) āˆˆ Types } Module = { f(x,y,..) | p(x,y) āˆˆ Domain Rules } ā€¢ domain function ā€¢ on an object of types x, y ā€¢ composes with other functions ā€¢ closed under composition ā€¢ business rules Domain Algebra Domain Algebra
  • 51. Given all the properties of algebra, can we consider algebraic composition to be the basis of designing, implementing and modularizing domain models ?
  • 52. Client places order - ļ¬‚exible format 1
  • 53. Client places order - ļ¬‚exible format Transform to internal domain model entity and place for execution 1 2
  • 54. Client places order - ļ¬‚exible format Transform to internal domain model entity and place for execution Trade & Allocate to client accounts 1 2 3
  • 55. def fromClientOrder: ClientOrder => Order def execute(market: Market, brokerAccount: Account) : Order => List[Execution] def allocate(accounts: List[Account]) : List[Execution] => List[Trade] trait Trading { } trait TradeComponent extends Trading with Logging with Auditing algebra of domain behaviors / functions functions aggregate upwards into modules modules aggregate into larger modules
  • 56. .. so we have a decent algebra of our module, the names reļ¬‚ect the appropriate artifacts from the domain (ubiquitous language), the types are well published and we are quite explicit in what the behaviors do ..
  • 57. 1. Compositionality - How do we compose the 3 behaviors that we published to generate trade in the market and allocate to client accounts ? 2. Side-effects - We need to compose them alongside all side-effects that form a core part of all non trivial domain model implementations
  • 58. ā€¢ Error handling ? ā€¢ throw / catch exceptions is not RT ā€¢ Partiality ? ā€¢ partial functions can report runtime exceptions if invoked with unhandled arguments (violates RT) ā€¢ Reading conļ¬guration information from environment ? ā€¢ may result in code repetition if not properly handled ā€¢ Logging ? ā€¢ side-effects Side-effects
  • 59. Side-effects ā€¢ Database writes ā€¢ Writing to a message queue ā€¢ Reading from stdin / ļ¬les ā€¢ Interacting with any external resource ā€¢ Changing state in place
  • 61. .. the semantics of compositionality .. in the presence of side-effects
  • 62. Algebra to the rescue ..
  • 63. Algebra to the rescue .. of types
  • 64. Abstract side-effects into data type constructors
  • 65. Abstract side-effects into data type constructors, which we call Effects ..
  • 66. Option[A] Either[A,B] (partiality) (disjunction) List[A] (non-determinism) Reader[E,A] (read from environment aka dependency Injection) Writer[W,A] (logging) State[S,A] (state management) IO[A] (external side-effects) .. and there are many many more ..
  • 67. F[A] The answer that the effect computesThe additional stuff modeling the computation
  • 68. ā€¢ The F[_] that we saw is an opaque type - it has no denotation till we give it one ā€¢ The denotation that we give to F[_] depends on the semantics of compositionality that we would like to have for our domain model behaviors
  • 69. def fromClientOrder: ClientOrder => F[Order] def execute(market: Market, brokerAccount: Account) : Order => F[List[Execution]] def allocate(accounts: List[Account]) : List[Execution] => F[List[Trade]] trait Trading[F[_]] { } Effect Type
  • 70. ā€¢ Just the Algebra ā€¢ No denotation, no concrete type ā€¢ Explicitly stating that we have eļ¬€ectful functions here def fromClientOrder: ClientOrder => F[Order] def execute(market: Market, brokerAccount: Account) : Order => F[List[Execution]] def allocate(accounts: List[Account]) : List[Execution] => F[List[Trade]] trait Trading[F[_]] { } Effect Type
  • 71. ā€¢ .. we have intentionally kept the algebra open for interpretation .. ā€¢ .. there are use cases where you would like to have multiple interpreters for the same algebra ..
  • 72. The Program def tradeGeneration[M[_]: Monad](T: Trading[M]) = for { order <- T.fromClientOrder(cor) executions <- T.execute(m1, ba, order) trades <- T.allocate(List(ca1, ca2, ca3), executions) } yield trades
  • 73. class TradingInterpreter[F[_]] (implicit me: MonadError[F, Throwable]) extends Trading[F] { def fromClientOrder: ClientOrder => F[Order] = makeOrder(_) match { case Left(dv) => me.raiseError(new Exception(dv.message)) case Right(o) => o.pure[F] } def execute(market: Market, brokerAccount: Account) : Order => F[List[Execution]] = ... def allocate(accounts: List[Account]) : List[Execution] => F[List[Trade]] = ... } One Sample Interpreter
  • 74. ā€¢ .. one lesson in modularity - commit to a concrete implementation as late as possible in the design .. ā€¢ .. we have just indicated that we want a monadic effect - we havenā€™t committed to any concrete monad type even in the interpreter ..
  • 75. The Program def tradeGeneration[M[_]: Monad](T: Trading[M]) = for { order <- T.fromClientOrder(cor) executions <- T.execute(m1, ba, order) trades <- T.allocate(List(ca1, ca2, ca3), executions) } yield trades import cats.effect.IO object TradingComponent extends TradingInterpreter[IO] tradeGeneration(TradingComponent).unsafeRunSync
  • 76. The Program def tradeGeneration[M[_]: Monad](T: Trading[M]) = for { order <- T.fromClientOrder(cor) executions <- T.execute(m1, ba, order) trades <- T.allocate(List(ca1, ca2, ca3), executions) } yield trades import monix.eval.Task object TradingComponent extends TradingInterpreter[Task] tradeGeneration(TradingComponent)
  • 77. The Program def tradeGenerationLoggable[M[_]: Monad] (T: Trading[M], L: Logging[M]) = for { _ <- L.info("starting order processing") order <- T.fromClientOrder(cor) executions <- T.execute(m1, ba, order) trades <- T.allocate(List(ca1, ca2, ca3), executions) _ <- L.info("allocation done") } yield trades object TradingComponent extends TradingInterpreter[IO] object LoggingComponent extends LoggingInterpreter[IO] tradeGenerationLoggable(TradingComponent, LoggingComponent).unsafeRunSync
  • 78. Raise the level of abstraction trait Trading[F[_]] { def fromClientOrder : Kleisli[F, ClientOrder, Order] def execute(market: Market, brokerAccount: Account) : Kleisli[F, Order, List[Execution]] def allocate(accounts: List[Account]) : Kleisli[F, List[Execution], List[Trade]] }
  • 79. The Program def tradeGeneration[M[_]: Monad](T: Trading[M]) : Kleisli[M, ClientOrder, List[Trade]] = { T.fromClientOrder andThen T.execute(m1, ba) andThen T.allocate(List(ca1, ca2, ca3)) } object TradingComponent extends TradingInterpreter[IO] val tk = tradeGeneration(TradingComponent) tk(cor).unsafeRunSync
  • 81. - Rob Norris at scale.bythebay.io talk - 2017 (https://www.youtube.com/ watch?v=po3wmq4S15A) ā€œEffects and side-effects are not the same thing. Effects are good, side-effects are bugs.Their lexical similarity is really unfortunate because people often conļ¬‚ate the two ideasā€
  • 82.
  • 83.
  • 84.
  • 85. Takeaways ā€¢ Algebra scales from that of one single data type to an entire bounded context ā€¢ Algebras compose enabling composition of domain behaviors ā€¢ Algebras let you focus on the compositionality without any context of implementation ā€¢ Statically typed functional programming is programming with algebras
  • 86. Takeaways ā€¢ Abstract early, interpret as late as possible ā€¢ Abstractions / functions compose only when they are abstract and parametric ā€¢ Modularity in the presence of side-effects is a challenge ā€¢ Effects as algebras are pure values that can compose based on laws ā€¢ Honor the law of using the least powerful abstraction that works
  • 87. From the Bible ā€œName classes and operations to describe their effect and purpose, without reference to the means by which they do what they promise.This relieves the client developer of the need to understand the internals.These names should conform to the UBIQUITOUS LANGUAGE so that team members can quickly infer their meaning. Write a test for a behavior before creating it, to force your thinking into client developer mode.ā€ - Eric Evans (Domain Driven Design) in the chapter on Supple Design, while discussing Intention Revealing Interfaces
  • 88. ā€¢ All names are from the domain vocabulary ā€¢ Just the algebra describing the promise, no implementation details ā€¢ Purpose and eļ¬€ect explicit - yes, literally explicit with eļ¬€ects def fromClientOrder: ClientOrder => F[Order] def execute(market: Market, brokerAccount: Account) : Order => F[List[Execution]] def allocate(accounts: List[Account]) : List[Execution] => F[List[Trade]] trait Trading[F[_]] { }
  • 89. From the Bible ā€œPlace as much of the logic of the program as possible into functions, operations that return results with no observable side- effects.ā€ - Eric Evans (Domain Driven Design) in the chapter on Supple Design, while discussing Side-Eļ¬€ect-Free Functions
  • 90. def tradeGeneration[M[_]: Monad](T: Trading[M]) = for { order <- T.fromClientOrder(cor) executions <- T.execute(m1, ba, order) trades <- T.allocate(List(ca1, ca2, ca3), executions) } yield trades ā€¢ The program tradeGeneration is completely side-eļ¬€ect free. It generates a pure value. ā€¢ Since the program is pure, you can interpret it in many ways (as we saw earlier). ā€¢ The side-eļ¬€ects occur only when you submit the program to the run time system. ā€¢ This is also an example where using algebraic & functional approach we get a clear separation between the building of an abstraction and executing it.
  • 91. From the Bible ā€œWhen it ļ¬ts, deļ¬ne an operation whose return type is the same as the type of its argument(s). If the implementer has state that is used in the computation, then the implementer is effectively an argument of the operation, so the argument(s) and return value should be of the same type as the implementer. Such an operation is closed under the set of instances of that type.A closed operation provides a high-level interface without introducing any dependency on other concepts.ā€ - Eric Evans (Domain Driven Design) in the chapter on Supple Design, while discussing Closure of Operations
  • 92. trait Semigroup[A] { def combine(x: A, y: A): A } trait Monoid[A] extends Semigroup[A] { def empty: A } ā€¢ With algebraic modeling, you can encode the closure of operations through the algebra of a Monoid. ā˜… parametric ā˜… deļ¬ne the algebra once, implement it as many times based on the context ā˜… compositionality at the algebra level ā€¢ For stateful computation, use the algebra of the State Monad and manipulate state as a Monoid
  • 93.