SlideShare a Scribd company logo
Domain Logic Patterns
by Pavlo Livchak,
Software Engineer
www.eliftech.com
Contents
1. What is domain logic?
2. Domain logic patterns:
1. Transaction script
2. Domain model
3. Table module
4. Service layer
3. Conclusion
www.eliftech.com
What is domain logic?
▪ Domain logic describe the functional algorithms or business logic that handle the information
exchange between a database and a user interface.
▪ The Domain logic patterns examine different ways to implement the logic for your application.
▪ Main concern is the complexity of the application’s logic.
www.eliftech.com
Domain logic patterns
● Transaction Script
● Domain Model
● Table Module
● Service Layer
Taken from “Patterns of Enterprise Application Architecture” by Martin
Fowler
www.eliftech.com
Transaction script
● Organizes business logic by procedures where each procedure handles a single request
from the presentation
● A Transaction Script organizes all this logic primarily as a single procedure, making calls
directly to the database or through a thin database wrapper.
Transaction script
www.eliftech.com
Transaction script
Advantages:
● It is independent from other transactions
● Very simple to implement and understand
Disadvantages:
● Code duplication
For more complex domain logic, Domain model pattern should be used instead.
www.eliftech.com
Domain Model
● An object model of the domain that incorporates both behavior and data.
www.eliftech.com
Types of Domain model
● Simple Domain model
○ Looks very much like the database design with mostly one domain object for each
database table
○ Uses Active record
● Rich Domain model
○ Looks different from the database design, with inheritance, strategies, and other
patterns, and complex webs of small interconnected objects
○ Uses Data mapper
www.eliftech.com
When to use it?
● In cases, when you have complicated and changing business rules involving additional
operations like validation, calculation.
www.eliftech.com
Table module
▪ The Table Module pattern takes the middle road between a Domain Model and
Transaction Script.
▪ Using this approach the logic for the application is implemented as a set of components
called Table Modules.
▪ Your solution would contain a Table Module for each Table in your database. These
Table Modules implement the functionality related to the entity described in the table.
www.eliftech.com
Table module
www.eliftech.com
When to use it?
▪ Table module is very much based on table-oriented data, so we can use it when we
access tabular data using Record Set.
▪ Table module allows you to fit business logic into the application in a well-organized
manner, without losing the way the elements work on the tabular data.
www.eliftech.com
Service layer
▪ Service Layer defines an application’s boundary with a layer of services that establishes
a set of available operations and coordinates the application’s response in each
operation.
▪ It encapsulates the application’s business logic, controlling transactions and
coordinating responses in the implementation of its operations.
www.eliftech.com
Service layer
www.eliftech.com
Service layer
2 Basic Implementation variations are:
● Domain facade approach
○ Service Layer is implemented as a set of thin facades over a Domain model
○ The classes implementing the facades don’t implement any business logic. All logic
is implemented in Domain Model
● Operation script approach
○ Service Layer is implemented as a set of thicker classes that directly implement
application logic but delegate to encapsulated domain object classes for domain
logic.
○ The operations available to clients of a Service Layer are implemented as scripts,
organized several to a class defining a subject area of related logic.
www.eliftech.com
When to use it?
▪ The benefit of Service Layer is that it defines a common set of application operations
available to many kinds of clients and it coordinates an application’s response in each
operation.
▪ In an application with more than one kind of client of its business logic, and complex
responses in its use cases involving multiple transactional resources, it makes a lot of
sense to include a Service Layer with container-managed transactions, even in an
undistributed architecture.
www.eliftech.com
Conclusion
● Transaction Script: This pattern abstracts each business transaction into a Script object. The
transactions are then performed by running the script.
● Domain Model: This pattern manages the application's complexity within an object oriented
model. Using this approach the business functionality is implemented within the model.
● Table Module: Using this pattern, the data related to the business entities is contained within
DataSet, while the logic is maintained with Table Modules. Each Table Module contains
methods that act upon the DataSet.
● Service Layer: This pattern provides a layer through which client applications can access the
services offered by an application (or service).
www.eliftech.com
Don't forget to subscribe not to
miss our next presentations!
Find us at eliftech.com
Have a question? Contact us:
info@eliftech.com

More Related Content

PDF
Managing transactions on Ethereum with Apache Airflow
PPTX
Transaction
PPTX
Layered Architecture - Software Architecture Pattern
PPTX
Domain logic patterns of Software Architecture
PPTX
L07 Oranizing Domain Logic
PPTX
L13 Oranizing Domain Logic
PDF
L15 Organising Domain Layer
PPTX
Managing transactions on Ethereum with Apache Airflow
Transaction
Layered Architecture - Software Architecture Pattern
Domain logic patterns of Software Architecture
L07 Oranizing Domain Logic
L13 Oranizing Domain Logic
L15 Organising Domain Layer

Similar to Domain Logic Patterns (20)

PDF
Nina Grantcharova - Approach to Separation of Concerns via Design Patterns
PPTX
.NET Architecture for Enterprises
PDF
Mind Your Business. And Its Logic
PPTX
Pragmatic Architecture in .NET
PPTX
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
PDF
Commonly used design patterns
PPTX
Architecture Principles CodeStock
PPTX
Why you shouldnt use django for that
PPTX
Software Architecture Design Patterns
PPT
Designingapplswithnet
PPTX
SW Security Lec3 Securing architecture.pptx
PPTX
Design patterns fast track
PDF
Application architecture
PDF
Reinventing the Transaction Script (NDC London 2020)
PPTX
Design patterns - The Good, the Bad, and the Anti-Pattern
PPT
Domain Driven Design (DDD)
PPTX
Software Development: Beyond Training wheels
PPTX
Software Architecture
PPT
Architecting for Change: An Agile Approach
Nina Grantcharova - Approach to Separation of Concerns via Design Patterns
.NET Architecture for Enterprises
Mind Your Business. And Its Logic
Pragmatic Architecture in .NET
Design Pattern Mastery - Momentum Dev Con 19 Apr 2018
Commonly used design patterns
Architecture Principles CodeStock
Why you shouldnt use django for that
Software Architecture Design Patterns
Designingapplswithnet
SW Security Lec3 Securing architecture.pptx
Design patterns fast track
Application architecture
Reinventing the Transaction Script (NDC London 2020)
Design patterns - The Good, the Bad, and the Anti-Pattern
Domain Driven Design (DDD)
Software Development: Beyond Training wheels
Software Architecture
Architecting for Change: An Agile Approach
Ad

More from ElifTech (20)

PPTX
Go Concurrency Patterns
PPTX
Go Concurrency Basics
PPTX
Dive into .Net Core framework
PPTX
VR digest. August 2018
PPTX
JS digest. July 2018
PPTX
VR digest. July 2018
PPTX
IoT digest. July 2018
PPTX
VR digest. June 2018
PPTX
IoT digest. June 2018
PPTX
IoT digest. May 2018
PPTX
Object Detection with Tensorflow
PPTX
VR digest. May 2018
PPTX
Polymer: brief introduction
PPTX
JS digest. April 2018
PPTX
VR digest. April, 2018
PPTX
IoT digest. April 2018
PPTX
IoT digest. March 2018
PPTX
VR digest. March, 2018
PPTX
VR digest. February, 2018
PPTX
IoT digest. February 2018
Go Concurrency Patterns
Go Concurrency Basics
Dive into .Net Core framework
VR digest. August 2018
JS digest. July 2018
VR digest. July 2018
IoT digest. July 2018
VR digest. June 2018
IoT digest. June 2018
IoT digest. May 2018
Object Detection with Tensorflow
VR digest. May 2018
Polymer: brief introduction
JS digest. April 2018
VR digest. April, 2018
IoT digest. April 2018
IoT digest. March 2018
VR digest. March, 2018
VR digest. February, 2018
IoT digest. February 2018
Ad

Recently uploaded (20)

PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
PPTX
ai tools demonstartion for schools and inter college
PDF
Nekopoi APK 2025 free lastest update
PDF
Design an Analysis of Algorithms I-SECS-1021-03
PDF
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
PDF
Understanding Forklifts - TECH EHS Solution
PDF
medical staffing services at VALiNTRY
PPTX
CHAPTER 2 - PM Management and IT Context
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PDF
Which alternative to Crystal Reports is best for small or large businesses.pdf
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PPTX
Transform Your Business with a Software ERP System
PDF
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
PPTX
history of c programming in notes for students .pptx
PDF
Upgrade and Innovation Strategies for SAP ERP Customers
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
L1 - Introduction to python Backend.pptx
PDF
wealthsignaloriginal-com-DS-text-... (1).pdf
PPTX
Essential Infomation Tech presentation.pptx
PPTX
VVF-Customer-Presentation2025-Ver1.9.pptx
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
ai tools demonstartion for schools and inter college
Nekopoi APK 2025 free lastest update
Design an Analysis of Algorithms I-SECS-1021-03
EN-Survey-Report-SAP-LeanIX-EA-Insights-2025.pdf
Understanding Forklifts - TECH EHS Solution
medical staffing services at VALiNTRY
CHAPTER 2 - PM Management and IT Context
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
Which alternative to Crystal Reports is best for small or large businesses.pdf
Wondershare Filmora 15 Crack With Activation Key [2025
Transform Your Business with a Software ERP System
Addressing The Cult of Project Management Tools-Why Disconnected Work is Hold...
history of c programming in notes for students .pptx
Upgrade and Innovation Strategies for SAP ERP Customers
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
L1 - Introduction to python Backend.pptx
wealthsignaloriginal-com-DS-text-... (1).pdf
Essential Infomation Tech presentation.pptx
VVF-Customer-Presentation2025-Ver1.9.pptx

Domain Logic Patterns

  • 1. Domain Logic Patterns by Pavlo Livchak, Software Engineer
  • 2. www.eliftech.com Contents 1. What is domain logic? 2. Domain logic patterns: 1. Transaction script 2. Domain model 3. Table module 4. Service layer 3. Conclusion
  • 3. www.eliftech.com What is domain logic? ▪ Domain logic describe the functional algorithms or business logic that handle the information exchange between a database and a user interface. ▪ The Domain logic patterns examine different ways to implement the logic for your application. ▪ Main concern is the complexity of the application’s logic.
  • 4. www.eliftech.com Domain logic patterns ● Transaction Script ● Domain Model ● Table Module ● Service Layer Taken from “Patterns of Enterprise Application Architecture” by Martin Fowler
  • 5. www.eliftech.com Transaction script ● Organizes business logic by procedures where each procedure handles a single request from the presentation ● A Transaction Script organizes all this logic primarily as a single procedure, making calls directly to the database or through a thin database wrapper. Transaction script
  • 6. www.eliftech.com Transaction script Advantages: ● It is independent from other transactions ● Very simple to implement and understand Disadvantages: ● Code duplication For more complex domain logic, Domain model pattern should be used instead.
  • 7. www.eliftech.com Domain Model ● An object model of the domain that incorporates both behavior and data.
  • 8. www.eliftech.com Types of Domain model ● Simple Domain model ○ Looks very much like the database design with mostly one domain object for each database table ○ Uses Active record ● Rich Domain model ○ Looks different from the database design, with inheritance, strategies, and other patterns, and complex webs of small interconnected objects ○ Uses Data mapper
  • 9. www.eliftech.com When to use it? ● In cases, when you have complicated and changing business rules involving additional operations like validation, calculation.
  • 10. www.eliftech.com Table module ▪ The Table Module pattern takes the middle road between a Domain Model and Transaction Script. ▪ Using this approach the logic for the application is implemented as a set of components called Table Modules. ▪ Your solution would contain a Table Module for each Table in your database. These Table Modules implement the functionality related to the entity described in the table.
  • 12. www.eliftech.com When to use it? ▪ Table module is very much based on table-oriented data, so we can use it when we access tabular data using Record Set. ▪ Table module allows you to fit business logic into the application in a well-organized manner, without losing the way the elements work on the tabular data.
  • 13. www.eliftech.com Service layer ▪ Service Layer defines an application’s boundary with a layer of services that establishes a set of available operations and coordinates the application’s response in each operation. ▪ It encapsulates the application’s business logic, controlling transactions and coordinating responses in the implementation of its operations.
  • 15. www.eliftech.com Service layer 2 Basic Implementation variations are: ● Domain facade approach ○ Service Layer is implemented as a set of thin facades over a Domain model ○ The classes implementing the facades don’t implement any business logic. All logic is implemented in Domain Model ● Operation script approach ○ Service Layer is implemented as a set of thicker classes that directly implement application logic but delegate to encapsulated domain object classes for domain logic. ○ The operations available to clients of a Service Layer are implemented as scripts, organized several to a class defining a subject area of related logic.
  • 16. www.eliftech.com When to use it? ▪ The benefit of Service Layer is that it defines a common set of application operations available to many kinds of clients and it coordinates an application’s response in each operation. ▪ In an application with more than one kind of client of its business logic, and complex responses in its use cases involving multiple transactional resources, it makes a lot of sense to include a Service Layer with container-managed transactions, even in an undistributed architecture.
  • 17. www.eliftech.com Conclusion ● Transaction Script: This pattern abstracts each business transaction into a Script object. The transactions are then performed by running the script. ● Domain Model: This pattern manages the application's complexity within an object oriented model. Using this approach the business functionality is implemented within the model. ● Table Module: Using this pattern, the data related to the business entities is contained within DataSet, while the logic is maintained with Table Modules. Each Table Module contains methods that act upon the DataSet. ● Service Layer: This pattern provides a layer through which client applications can access the services offered by an application (or service).
  • 18. www.eliftech.com Don't forget to subscribe not to miss our next presentations! Find us at eliftech.com Have a question? Contact us: info@eliftech.com

Editor's Notes

  • #4: Отже перший пункт - що таке domain logic. Domain logic - це функціЇ, які виконує дана система. Відповідно бізнес-логіка входить в це визначення. Таким чином domain logic patterns - це патерни організації логіки системи, що розробляється. Вибір патернів залежить від складності системи, а саме від моделей даних і їх взаємодії між собою.
  • #5: Тепер перейдемо до самих патернів. Всі вони висвітлені в цій книзі авторства Мартіна Фаулера, одно з основоположників методології Agile. Отже, ми маємо 4 патерни. Далі поговоримо про них детальніше.
  • #6: Перший - transaction script. Хочу зразу прояснити один момент. Тут слово transaction немає ніякого відношення до SQL-транзакцій чи чогось подібно Тут під транзакцією розуміється ширше поняття. Тобто, транзакція - це просто певна група операції. Це, власне, і є визначенням патерна transaction script. Ми маємо певну процедуру, яка виконує всі необхідні дії. Наприклад, ми маємо функцію “придбати товар”, що включає в себе створення об’єкту “замовлення”, перевірки чи товар в замовленні є доступним і збереження замовлення в базі даних. Для виконання всіх цих дій ми маємо одну функцію де спілкування з БД відбувається напряму без використання посередників типу ORM-ки.
  • #7: Отже, основною перевагою все ж таки є простота. В нас є одна функція, немає явних моделей даних. Вся робота йде напряму. Але по мірі ускладнення системи код для спілкування з БД почне повторюватись. Наприклад, в двох різних транзакціях буде виконуватись запит на зчитування інформації про товар з бази. Зразу виникає думка про те, що цю операцію можна вписати в якийсь клас. І тут виходить на сцену наш наступний паттерн.
  • #8: Domain model - це модель предметної області. Або більш приземлено, це сукупність моделей даних і їх взаємодія, що описують дану предметну область. Я впевнений, що кожен з присутніх розробників зустрічався або використовував цей патерн, навіть не знаючи про нього. Це ORM (Object-relational mapping). На даній схемі, спрошено показана операція покупка товарів юзером.
  • #9: Domain model можна поділити на дві категорії. SDM and RDM відповідно. Випадок сімпл, це типова архітектура з використанням ORM - маємо модель і таблицю, що їй відповідає. Робота з базою даних в цьому випадку є дуже простою. Ми просто викликаємо на екземплярі моделі відповідний метод. У другому випадку, rich - в системі використовуються моделі, які комбінацією інших моделей або результатом виконання певних функцій, що не мають відповідної таблиці в БД. Як наслідок, потрібен Data Mapper для збереження даних з таких моделей, який перепише дані в екземпляри моделей, які мають таблиці.
  • #10: Такий патерн підходить для систем де є велика кількість різних видів взаємодії між моделями. Такий підхід є найгнучкішим і запобігає дублюванню коду. Але в свою чергу він вимагає попереднього аналізу, щоб якомога точніше змоделювати дану предметну область.
  • #11: Наступний патерн - Table module. Цей патерн є чимось середнім між transaction scripts i domain model. Специфіка наступна - для кожної таблиці створюється окремий клас Table module. Далі вся робота з цією таблицею(створення, читання, редагування, видалення) буде проходити через цей клас. Це основною відмінністю між патерном Domain model. У випадку Domain model, всі операції проводяться на екземплярі моделі, а у цьому випадку ми викликаємо відповідну функцію класу Table Module з відповідними параметрами. Тобто екземплярів моделі може бути багато, а table module - один.
  • #12: Даний алгоритм роботи пояснює дана схема. Зверху ми маємо 4 колонки. 1-й - presentation - є певним класом, що відповідає за презентацію даних, 2-й table data gateway - формує дані у відповідний датасет, 3-тя - це база даних або клас що відповідає за роботу з нею, І 4-та це власне наш table module. Він приймає в себе датасет. Далі всі операції над даними спочатку виконуються з цим датасетом, де вони валідуються, а вже далі зміни переходять у базу даних.
  • #13: Коли ж це викорстовувати? Очевидно, коли в нас дані зберігаються в таблицях. Такий підхід зберігає просту і зрозумілу структуру даних. Також ми абстрагуємося від джерела даних. Клієнт не знає чи прийшли дані з бази чи з іншого місця оскільки всі дані читаються з датаСету. З метою тестуванні ми можемо замокати дані напряму в датасет і десь на клієнті або юзерінтерфейсі не буде ніякої різниці.
  • #14: І останній патерн - Service Layer. Він сильно відрізняється від попередніх. Попередні патерни включали в себе реалізацію бізнес-логіки і роботу з джерелом даних. Патерн Service layer реалізує інтерфейс для роботи з бізнес-логікою. Тобто є чимось зовнішнім по відношенню до того ж Domain model.
  • #15: Цей момент прекрасно ілюструє цей малюнок. Тут наш Service layer є інтерфейсом Domain model, в я кому вже, в свою чергу, реалізована бізнес-логіка і робота з бд. Тут показані різні види клієнтів. Ці клієнти можуть бути частиною нашої системи або якоїсь іншої, які намагається дістати дані чи виконати якісь дії в нашій програмі.
  • #16: Існує два варіанти імплементації цього патерну. Domain facade approach - множина функцій-фасадів, що дають змогу працювати з певними функціями Domain model. Вони в собі не містять бізнес-логіки І другий, Operation script - тут все цікавіше. Ми вже маємо певні класи, які відповідають за зв’язок з певними частинами Domain model. Мікросервісна архітектура є прикладом реалізації цього варіанту патерна: ми має певний сервіс, що відповідає за роботу з певною частиною Domain model.
  • #17: Основною перевагою використання цього патерну є те, що він дає нам змогу інкапсулювати в ньому можливість роботи з різними видами клієнтів, не змінюючи при цьому domain model. В загальному, також спрощується робота з Domain model.
  • #18: На цьому слайді ми маємо загальний висновок. Отже, transaction script - маємо одну процедуру, яка виконує всю роботу. Domain model - ми реалізуємо модель предметної області шляхом створення сутностей і взаємодії між ними Table module - створюється клас для роботи з таблицею. Всі операції для роботи з цією таблицею виконує тільки цей клас І Service Layer - визначає інтерфейс для роботи з моделлю предметної області шляхом створення спеціальних фасадів або класів-сервісів.