1. PADRÕES DE APLICAÇÕES
EMPRESARIAIS
ATRAVÉS DE EXEMPLO
Lição para provas públicas para professor
coordenador na área científica de engenharia
informática
Paulo Gandra Sousa
pag@isep.ipp.pt
2. Enquadramento da lição
1
Sessão de “Introdução” de Seminário
Preparar para o desenvolvimento de aplicações em
camadas
Usando as boas práticas da comunidade
Baseado no livro “Patterns of enterprise application
architecture” de Martin Fowler
Através de um exemplo
3. Inclusão em UC
4
Passado Presente Eventual
futuro
• EINF • PARS • PARS
• PARS • PSIDI • PPROG
• Mobilidade • EAPLI • EAPLI
Erasmus • ARQSI
• Formação
ao exterior
4. Língua utilizada
Inglês
Partilha dos materiais
http://www.slideshare.net/pagsousa
Reutilização de material do Seminário de
mobilidade Erasmus
6. Goal
Understand how to develop layered
enterprise applications by using
available best practices.
7. Scope
8
In scope Out of scope
Layered architectures ORM
Business logic User Interaction
Data access SOA
Distribution Technology-dependent
best practices
...
8. In every project you have to decide
9
How to code the Business logic?
How to represent business entities?
How to persist its state?
How to guarantee data coherence?
How to handle application distribution?
...
9. Driving forces
10
Ever growing technical complexity
Networks, internet (www)
More “potent” OS
Higher level abstraction libraries/midleware/VM
Integration with 3rd party applications
Business
Higher demand from business
Higher expectation from business
Integration with 3rd party businesses
10. Answers are available. Here.
11
How to code the Business logic
How to represent business entities
How to persist its state
How to guarantee data coherence
How to handle application distribution
11. How will we do it?
12
Best practices
(patterns)
Layered Sample
Architecture Application
Enterprise Applications
12. Sessions
13
1. Introduction
2. Business entities
3. Table-oriented Business logic and data access
4. Object-oriented Business logic and data access
5. Some improvements
6. Distributed Applications
7. Synopsis
14. Session Goals
15
Understand the concept of
Enterprise application
Software pattern
Software architecture
Layered architectures
Get acquainted with the sample problem
Get an overview of the rest of the seminar
18. Enterprise application
19
Business-critical functionality
Large quantity of concurrently accessed data
Large number of screens
Complex (ilogic) business rules
Shared resources (sometimes with no ownership)
Conceptual dissonance
Integration
23. “Each pattern describes a problem that
occurs over and over again in our
environment and then describes the core
of the solution to that problem in such a
way that you can use this solution a
million times over without ever doing it
the same way twice.”
Christopher Alexander (architect)
1979
24. “A Software Design Pattern names,
abstracts, and identifies the key aspects
of a common design structure that make
it useful for creating a reusable object-
oriented design.”
Design Patterns-Elements of Reusable Object-oriented
Software, Gamma et al. (Gang of Four)
1995
25. “A particular recurring design problem
that arises in specific design contexts,
and presents a well-proven generic
scheme for its solution. The solution
scheme is specified by describing its
constituent components, their
responsibilities and relationships, and
the ways in which they collaborate”
Pattern Oriented Software Architecture, volume 1
Bushman et al. 1996
26. To sum up:
27
General Recuring Context Pattern
solution problem
27. A pattern is
28
a set of (field-tested) best practices
found not invented
a way to facilitate communication
Most of the time used in combination with other
patterns
30. Challenges
31
No direct code reuse
Pattern overload
Experience-based validation
Hard work integrating patterns in the development
process
31. Key Principles
Program to an interface not an implementation
Decreases coupling/dependencies among classes
Favour composition instead of inheritance
Don’t inherit behaviour you don’t need. Allow for
implementation changes
Consider what should be variable in your design
Encapsulate what varies and allow for substitution via
common interface
32. Pattern description
33
name Contributes to the pattern
vocabulary
synopsis Short description of the problem the
pattern will solve.
forces Requirements, considerations, or
necessary conditions
solution The essence of the solution
counter forces Reasons for not using the pattern.
related patterns Possible alternatives in the design.
33. At this final stage [...] the patterns
aren’t important. The forces in the
problem domain and how to resolve
them are.
Christopher Alexander (1979)
35. “Software Architecture is the
fundamental organization of a system,
embodied in its components, their
relationships to each other and the
environment, and the principles
governing its design and evolution.“
ANSI/IEEE Std 1471-2000, Recommended Practice for
Architectural Description of Software-Intensive Systems
36. “The software architecture of a program or
computing system is the structure or structures
of the system, which comprise software
elements, the externally visible properties of
those elements, and the relationships among
them.
"Externally visible” properties refers to those
assumptions other elements can make of an
element, such as its provided services,
performance characteristics, fault handling,
shared resource usage, and so on. “
Software Architecture in Practice (2003)
37. A reference model: 3-Layers
38
Application
Data
Presentation Business
Access
Logic Logic
Logic
38. PGS14
3 layers
39
PessoaForm
Presentation + ButtonOK_Click ( )
Layer + Close ( ) Business rules
+
Persistence
Pessoa commands
- Nome : string
- dtNascimento : DateTime
Business Logic + SetDataNascimento ( [in] dt : DateTime )
+ SetDataNascimento ( [in] ano : int , [in] mes : int , [in] dia : int )
Layer + GetIdade ( ) : int
+ LoadById ( [in] ID : int ) : Pessoa
+ Save ( )
A generic
component forces
the business
AcessoDados
Layer to know
Data Access + AbreConexao ( ) : IConnection SQL
+ ExecutaSelect ( [in] sql : string ) : DataSet
Layer + ExecutaUpdate ( [in] sql : string ) : int Thus it is not a
+ FechaConexao ( [in] cnx : IConnection )
data layer
39. Slide 40
PGS14 incluir estes 3 slides?
Paulo G Sousa; 26-02-2010
40. 3 layers
40
PessoaForm
+ ButtonOK_Click ( )
+ Close ( )
Pessoa
Business rules - Nome : string
- dtNascimento : DateTime
+
+ SetDataNascimento ( [in] dt : DateTime )
Persistence + SetDataNascimento ( [in] ano : int , [in] mes : int , [in] dia : int )
commands + GetIdade ( ) : int
+ LoadById ( [in] ID : int ) : Pessoa
+ Save ( )
Methods for
PessoaDAL
data access
+ Insert ( [in] nome : string , [in] dtNasc : DateTime ) : int hidding the
+ Update ( [in] int ID , [in] nome : string , [in] dtNasc : DateTime )
+ Delete ( [in] ID : int ) implementation
+ FindByID ( [in] ID : in ) : DataRow
aspects of
persistence
41. 3 layers
41
PessoaForm
Data access
Pessoa Morada
component
DAL
PessoaDAL MoradaDAL
+ Insert ( [in] nome : string , [in] dtNasc : DateTime ) : int + FindByID ( )
+ Update ( [in] int ID , [in] nome : string , [in] dtNasc : DateTime ) + Update ( )
+ Delete ( [in] ID : int ) + Delete ( )
+ FindByID ( [in] ID : in ) : DataRow + Insert ( )
BaseDAL
+ CONNECTION : string
+ AbrirConexao ( ) : IConnection
Internal
+ ExecutarQuery ( [in] sql : string ) : DataSet (package)
+ ExecutarUpdate ( [in] sql : string ) : int
+ FindByID ( [in] tabela : string , [in] campo : string , [in] chave : int ) : DataRow base class
45. The problem: Revenue Recognition
45
Customer Contract Product
1 *
+ name + revenue + name
* + dateSigned 1
1
WordProcessor SpreadSheet
*
RevenueRecognition
+ dateRecognition DataBase
+ amount
Different payment rules
WP – all at once (t)
DB – 3 payments: t, t+30, t+60
SS – 3 payments: t, t+60, t+90
(From Martin Fowler’s PoEAA book)
46. Requirements
46
For a given contract, calculate when each revenue
will happen and the amount due
For a given contract, calculate how much revenue it
has generated as of a certain date
48. Relational model
48
«table»
TRevenueRecognitions
+ «Column» ID : int
+ «Column» contractID : int
+ «Column» dateRecognition : date
+ «Column» amount : currency
«table»
«table»
TContracts
«table» TProducts
TCustomers + «Column» ID : int
+ «Column» ID : int
+ «Column» productID : int
+ «Column» ID : int + «Column» type : varchar
+ «Column» customerID : int
+ «Column» name : varchar + «Column» name : varchar
+ «Column» revenue : currency
+ «Column» dateSigned : date
49. The workbench application
49
Architectural
style
output
Business
operations
http://w2ks.dei.isep.ipp.pt/psousa/GetFile.aspx?file=PoEAAWorkbench.zip
50. Remember the questions?
50
The workbench will show
How to represent the business entities
How to persist its state
How to code the Business logic
How to guarantee data coherence
The workbench will not show
How to handle application distribution
51. The first big question
51
Table-oriented
Versus
Object-oriented
52. Architectural examples
52
Table oriented
Table Module + Table Data Gateway (DataSet)
Table Module + Table Data Gateway (Custom Classes)
Object-oriented
Domain Model + Active Record
Domain Model + Data Mapper
53. Architectural examples
53
Transaction Script using DataSet
Transaction Script
Transaction Script + Data Gateway
Transaction Script using Custom Classes
Transaction Script
Transaction Script + Row Data Gateway
Table Module
Table Module + Table Data Gateway (DataSet)
Table Module + Table Data Gateway (Custom Classes)
focus
Domain Model
Domain Model + Active Record
Domain Model + Data Mapper
54. Workbench’s architecture
54
Different arch.
Styles. These are the
classes to “look” at
RevenueGUI RevenueFacade implementation
Common
55. The RevenueFacade layer
55
A combination of a Factory, a
Singleton and a Façade
The desired implementation is
loaded into memory and an
instance of the specific
façade is created (reflection)
and returned to the GUI
The UI layer will then interact
with the business layer via the
IRevenueRecognition business
interface ignoring the actual
implementation
56. Pattern
Factory
56
Problem:
How to hide the details of object creation specially
when there are special conditions on how and which
object (interface implementation) to create?
Solution:
Create an object whose sole responsibility is to create
other objects based on context information and hiding
de details of that potentially complex creation
57. Pattern
Factory
57
Provides a way to hide complexity of object
creation
58. Pattern GoF
Façade
Problem:
Actual work is performed by two or more objects, but
you want to hide this level of complexity from the client.
Solution:
Create a facade object that receives the messages, but
passes commands on to the workers for completion.
59. Pattern GoF
Façade
59
Provide a unified interface to a set of interfaces in a subsystem.
Façade defines a higher-level interface that makes the subsystem
easier to use.
source: Design Patterns: Elements of Reusable Object-Oriented Software
60. Pattern GoF
Singleton
Problem:
You want to ensure that there is never more than one
instance of a given class.
Solution:
Make the constructor private, have a method that
returns just one instance, which is held inside the class
itself.
61. Pattern GoF
Singleton
61
Ensure a class has only one instance and provide a
global point of access to it.
soure: Design Patterns: Elements of Reusable Object-Oriented Software
64. Business entities
Record Set versus Custom class
One versus many
Relationships (networks, hierarchies, etc.)
XML
65. Table-oriented: Packages
TM+TDG TM+TDG+CC
UI UI
«table module» «table module» Entities
BLL BLL
These classes
«table data gateway»
DAL
«table data gateway» have only
DAL
attributes
Uses the plaform
Record Set
66. Table oriented: Table Module
Contract
+ Contract ( )
+ RecognizedRevenue ( [in] contractID : int , [in] asOf : DateTime ) : Money
+ CalculateRevenueRecognitions ( [in] contractID : int )
+ GetContracts ( ) : DataSet
+ GetContractsByProduct ( [in] productID : int ) : DataSet
+ GetContractsByCustomer ( [in] customerID : int ) : DataSet
Customer
One class per
table + Customer ( )
+ GetCustomers ( ) : DataTable
handles all the
records in the
table Product
+ Product ( )
+ GetProducts ( ) : DataTable
71. Problems with domain model
How to avoid networks of objects to be fully loaded into
memory when only a few “fields” are necessary
Lazy Load
How to guarantee that there are no multiple in memory
representations of the same “db entity”
Identity Field
Identity Map
How to allow for variations of the same algorithm?
Strategy
To embed each recognition rule in the Domain model
74. Session synopsis
74
Introduced the concept of
Enterprise application
Software pattern
Software architecture
Layered architectures
Presented the sample problem
Presented an overview of the rest of the seminar
75. At this final stage [...] The patterns
aren’t important. The forces in the
problem domain and how to resolve
them are.
Christopher Alexander (1979)
76. Patterns of Enterprise
Applications (by Example)
Paulo Sousa
76
ISEP/IP
pag@isep.ipp.pt http://linkedin.com/in/pagsousa
P
78. Bibliography
78
Fowler, Martin. Patterns of Enterprise Application Architecture. Adisson-
Wesley.
Erich Gamma, Richard Helm, Ralph Johnson, John Vissides. Design patterns :
elements of reusable object-oriented software. Adisson-Wesley.
Frank Buschmann, Regine Meunier, Hans Rohnert, Peter Sommerlad, Michael
Stal. Pattern-oriented Software Architecture: System of Patterns.
Buschmann, F.; Henney, K. And Schmidt, D. (2007) Pattern-Oriented
Software Architecture: A Pattern Language for Distributed Computing,
Volume 4. Willey.
Deepak Alur, John Crupi and Dan Malks. Core J2EE Patterns: Best Practices
and Design Strategies. Prentice Hall / Sun Microsystems Press.
http://java.sun.com/blueprints/corej2eepatterns/index.html
Enterprise Solution Patterns Using Microsoft .NET. Microsoft Press.
http://msdn.microsoft.com/architecture/patterns/default.aspx?pull=/librar
y/en-us/dnpatterns/html/Esp.asp
Designing Data Tier Components and Passing Data Through Tiers. Microsoft
Patterns & Practices. http://msdn.microsoft.com/library/?url=/library/en-
us/dnbda/html/BOAGag.asp?frame=true
79. Bibliography
79
Domain logic and SQL. Martin Fowler.
http://www.martinfowler.com/articles/dblogic.htm
l
Why extends is evil. Allen Holub
http://www.javaworld.com/javaworld/jw-08-
2003/jw-0801-toolbox.html
Why getter and setter methods are evil . Allen Holub
http://www.javaworld.com/javaworld/jw-09-
2003/jw-0905-toolbox.html
Domain logic and SQL. Martin Fowler.
http://www.martinfowler.com/articles/dblogic.html
Public vs. Published interfaces. Martin Fowler.
http://www.martinfowler.com/ieeeSoftware/publi
shed.pdf
Don’t live with Broken windows
http://www.artima.com/intv/fixit.html
80. Pattern catalogs
80
GoF Design patterns (em C#)
http://www.dofactory.com/Patterns/Patterns.aspx
GoF & POSA Design patterns (em Java)
http://www.vico.org/pages/PatronsDisseny.html
Patterns of Enterprise Application architecture
http://martinfowler.com/eaaCatalog/
Core J2EE Patterns
http://www.corej2eepatterns.com
Enterprise Solution Patterns Using Microsoft .NET.
http://msdn.microsoft.com/architecture/patterns/default.aspx?pull=/librar
y/en-us/dnpatterns/html/Esp.asp
Patterns of Enterprise Application Integration
http://www.enterpriseintegrationpatterns.com/
Enterprise Java Patterns @ The Server Side
http://www.theserverside.com/patterns/index.tss
Microsoft Data Patterns
http://msdn.microsoft.com/architecture/patterns/default.aspx?pull=/librar
y/en-us/dnpatterns/html/Dp.asp