SlideShare uma empresa Scribd logo
1 de 18
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

Mais conteúdo relacionado

Semelhante a Domain Logic Patterns

Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...
Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...
Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...CodeScience
 
Private cloud reference model ms
Private cloud reference model msPrivate cloud reference model ms
Private cloud reference model mschrisjosewanjira
 
Peoplesoft PIA architecture
Peoplesoft PIA architecturePeoplesoft PIA architecture
Peoplesoft PIA architectureAmit rai Raaz
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE PatternsEmprovise
 
Beyond rails new
Beyond rails newBeyond rails new
Beyond rails newPaul Oguda
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2divzi1913
 
Salesforce Presentation
Salesforce PresentationSalesforce Presentation
Salesforce PresentationChetna Purohit
 
Clean architecture
Clean architectureClean architecture
Clean architecture.NET Crowd
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - TalkMatthias Noback
 
MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...
MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...
MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...Jitendra Bafna
 
TOLL MANAGEMENT SYSTEM
TOLL MANAGEMENT SYSTEMTOLL MANAGEMENT SYSTEM
TOLL MANAGEMENT SYSTEMvishnuRajan20
 
Toll management system (1) (1)
Toll management system (1) (1)Toll management system (1) (1)
Toll management system (1) (1)vishnuRajan20
 
Backend Basic in nodejs express and mongodb PPT.pdf
Backend  Basic in nodejs express and mongodb PPT.pdfBackend  Basic in nodejs express and mongodb PPT.pdf
Backend Basic in nodejs express and mongodb PPT.pdfsadityaraj353
 
Yotpo microservices
Yotpo microservicesYotpo microservices
Yotpo microservicesRon Barabash
 
1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.ppt1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.pptKalsoomTahir2
 
--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppt--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppteddielyndacanay0
 

Semelhante a Domain Logic Patterns (20)

SOA Design Patterns
SOA Design PatternsSOA Design Patterns
SOA Design Patterns
 
Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...
Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...
Technical Webinar: Patterns for Integrating Your Salesforce App with Off-Plat...
 
Private cloud reference model ms
Private cloud reference model msPrivate cloud reference model ms
Private cloud reference model ms
 
L07 Oranizing Domain Logic
L07 Oranizing Domain LogicL07 Oranizing Domain Logic
L07 Oranizing Domain Logic
 
Peoplesoft PIA architecture
Peoplesoft PIA architecturePeoplesoft PIA architecture
Peoplesoft PIA architecture
 
J2EE Patterns
J2EE PatternsJ2EE Patterns
J2EE Patterns
 
Beyond rails new
Beyond rails newBeyond rails new
Beyond rails new
 
Struts 2-overview2
Struts 2-overview2Struts 2-overview2
Struts 2-overview2
 
Salesforce Presentation
Salesforce PresentationSalesforce Presentation
Salesforce Presentation
 
Clean architecture
Clean architectureClean architecture
Clean architecture
 
Advanced web application architecture - Talk
Advanced web application architecture - TalkAdvanced web application architecture - Talk
Advanced web application architecture - Talk
 
MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...
MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...
MuleSoft Surat Virtual Meetup#27 - MuleSoft Runtime 4.4, Transit Gateway and ...
 
TOLL MANAGEMENT SYSTEM
TOLL MANAGEMENT SYSTEMTOLL MANAGEMENT SYSTEM
TOLL MANAGEMENT SYSTEM
 
Toll management system (1) (1)
Toll management system (1) (1)Toll management system (1) (1)
Toll management system (1) (1)
 
Backend Basic in nodejs express and mongodb PPT.pdf
Backend  Basic in nodejs express and mongodb PPT.pdfBackend  Basic in nodejs express and mongodb PPT.pdf
Backend Basic in nodejs express and mongodb PPT.pdf
 
Yotpo microservices
Yotpo microservicesYotpo microservices
Yotpo microservices
 
1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.ppt1588487811-chp-11-c-enterprise-application-integration.ppt
1588487811-chp-11-c-enterprise-application-integration.ppt
 
--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppt--Enterprise-Application-Integration.ppt
--Enterprise-Application-Integration.ppt
 
L13 Oranizing Domain Logic
L13 Oranizing Domain LogicL13 Oranizing Domain Logic
L13 Oranizing Domain Logic
 
J2 ee archi
J2 ee archiJ2 ee archi
J2 ee archi
 

Mais de ElifTech

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

Mais de ElifTech (20)

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

Último

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfkalichargn70th171
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVshikhaohhpro
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 

Último (20)

The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdfLearn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
Learn the Fundamentals of XCUITest Framework_ A Beginner's Guide.pdf
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Exploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the ProcessExploring iOS App Development: Simplifying the Process
Exploring iOS App Development: Simplifying the Process
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Optimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTVOptimizing AI for immediate response in Smart CCTV
Optimizing AI for immediate response in Smart CCTV
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 

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

Notas do Editor

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