lição prova professor coordenador

80
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 [email protected]

Upload: paulo-sousa

Post on 06-May-2015

2.090 views

Category:

Education


2 download

DESCRIPTION

slidedeck used for public contest for full professorship position at ISEP (2010/03/04)

TRANSCRIPT

PADRÕES DE APLICAÇÕESEMPRESARIAISATRAVÉS DE EXEMPLO

Lição para provas públicas para professor coordenador na área científica de engenhariainformática

Paulo Gandra [email protected]

Enquadramento da lição1

� Sessão de “Introdução” de Seminário

� Preparar para o desenvolvimento de aplicações emcamadas

� Usando as boas práticas da comunidade

� Baseado no livro “Patterns of enterprise application architecture” de Martin Fowler

� Através de um exemplo

Inclusão em UC4

Passado

• EINF

Presente

• PARS

Eventual futuro

• PARS• EINF• PARS• Mobilidade

Erasmus

• PARS• PSIDI• EAPLI

• PARS• PPROG• EAPLI• ARQSI• Formação

ao exterior

Língua utilizada

� Inglês

� Partilha dos materiais

� http://www.slideshare.net/pagsousa� http://www.slideshare.net/pagsousa

� Reutilização de material do Seminário de mobilidade Erasmus

PATTERNS OF ENTERPRISE APPLICATIONS (BY EXAMPLE)

Paulo [email protected]

Goal

Understand how to develop layered Understand how to develop layered enterprise applications by using

available best practices.

Scope

� Layered architectures

� Business logic

� ORM

� User Interaction

8

In scope Out of scope

Business logic

� Data access

� Distribution

User Interaction

� SOA

� Technology-dependent best practices

� ...

In every project you have to decide

� How to code the Business logic?

� How to represent business entities?

� How to persist its state?

9

� How to persist its state?

� How to guarantee data coherence?

� How to handle application distribution?

� ...

Driving forces10

� Ever growing technical complexity

� Networks, internet (www)

� More “potent” OS

� Higher level abstraction libraries/midleware/VM� 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

Answers are available. Here.

� How to code the Business logic

� How to represent business entities

11

� How to persist its state

� How to guarantee data coherence

� How to handle application distribution

How will we do it?12

Best practices(patterns)

SampleApplication

LayeredArchitecture

Enterprise Applications

Sessions

1. Introduction

2. Business entities

3. Table-oriented Business logic and data access

4. Object-oriented Business logic and data access

13

4. Object-oriented Business logic and data access

5. Some improvements

6. Distributed Applications

7. Synopsis

INTRODUCTION

Session 1

Session Goals15

� Understand the concept of

� Enterprise application

� Software pattern

� Software architecture� Software architecture

� Layered architectures

� Get acquainted with the sample problem

� Get an overview of the rest of the seminar

Session Agenda16

1. Enterprise applications

2. Patterns

3. Layered architectures

4. Sample problem & application4. Sample problem & application

5. PoEAA Preview

Part 1

Enterprise Applications

17

18

Enterprise application

� Business-critical functionality

� Large quantity of concurrently accessed data

� Large number of screens

� Complex (ilogic) business rules

19

� Complex (ilogic) business rules

� Shared resources (sometimes with no ownership)

� Conceptual dissonance

� Integration

Some Enterprise Applications20

Things that are not EA21

Part 2

Patterns

22

“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 way that you can use this solution a million times over without ever doing it

the same way twice.”

Christopher Alexander (architect)

1979

“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-it useful for creating a reusable object-

oriented design.”

Design Patterns-Elements of Reusable Object-oriented Software, Gamma et al. (Gang of Four)

1995

“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 constituent components, their responsibilities and relationships, and

the ways in which they collaborate”

Pattern Oriented Software Architecture, volume 1

Bushman et al. 1996

To sum up:27

General RecuringGeneral solution

Recuringproblem Context Pattern

A pattern is

� a set of (field-tested) best practices

� found not invented

28

� a way to facilitate communication

� Most of the time used in combination with other patterns

“Patterns are half-baked”

Martin Fowler

notnot

Challenges31

� No direct code reuse

� Pattern overload

� Experience-based validation

� Hard work integrating patterns in the development process

Key Principles

� Program to an interface not an implementation� Decreases coupling/dependencies among classes

� Favour composition instead of inheritanceDon’t inherit behaviour you don’t need. Allow for � 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

Pattern description33

name Contributes to the pattern vocabulary

synopsis Short description of the problem the pattern will solve. 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.

At this final stage [...] the patterns

aren’t important. The forces in the

problem domain and how to resolve problem domain and how to resolve

them are.

Christopher Alexander (1979)

Part 3

Layered Architecture

35

“Software Architecture is the fundamental organization of a system,

embodied in its components, their relationships to each other and the 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

“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)

A reference model: 3-Layers

Application

38

Presentation

Logic

Data

Access

Logic

Business

Logic

3 layers

PessoaForm

+ ButtonOK_Click ( )

+ Close ( )

Pessoa

- Nome : string

- dtNascimento : DateTime

Business rules+

Persistence commands

PresentationLayer

39

- dtNascimento : DateTime

+ SetDataNascimento ( [in] dt : DateTime )

+ SetDataNascimento ( [in] ano : int , [in] mes : int , [in] dia : int )

+ GetIdade ( ) : int

+ LoadById ( [in] ID : int ) : Pessoa

+ Save ( )

AcessoDados

+ AbreConexao ( ) : IConnection

+ ExecutaSelect ( [in] sql : string ) : DataSet

+ ExecutaUpdate ( [in] sql : string ) : int

+ FechaConexao ( [in] cnx : IConnection )

A generic component forces the business Layer to know SQLThus it is not a data layer

Data AccessLayer

Business LogicLayer

PGS14

Slide 40

PGS14 incluir estes 3 slides?Paulo G Sousa; 26-02-2010

3 layers

PessoaForm

+ ButtonOK_Click ( )

+ Close ( )

Pessoa

- Nome : string

- dtNascimento : DateTimeBusiness rules

+

40

- dtNascimento : DateTime

+ SetDataNascimento ( [in] dt : DateTime )

+ SetDataNascimento ( [in] ano : int , [in] mes : int , [in] dia : int )

+ GetIdade ( ) : int

+ LoadById ( [in] ID : int ) : Pessoa

+ Save ( )

PessoaDAL

+ Insert ( [in] nome : string , [in] dtNasc : DateTime ) : int

+ Update ( [in] int ID , [in] nome : string , [in] dtNasc : DateTime )

+ Delete ( [in] ID : int )

+ FindByID ( [in] ID : in ) : DataRow

Methods for data access hidding the

implementation aspects of

persistence

+ Persistence commands

3 layers

DAL

Data access component

PessoaForm

Pessoa

PessoaDAL

Morada

MoradaDAL

41

Internal (package) base class

PessoaDAL

+ Insert ( [in] nome : string , [in] dtNasc : DateTime ) : int

+ Update ( [in] int ID , [in] nome : string , [in] dtNasc : DateTime )

+ Delete ( [in] ID : int )

+ FindByID ( [in] ID : in ) : DataRow

BaseDAL

+ CONNECTION : string

+ AbrirConexao ( ) : IConnection

+ ExecutarQuery ( [in] sql : string ) : DataSet

+ ExecutarUpdate ( [in] sql : string ) : int

+ FindByID ( [in] tabela : string , [in] campo : string , [in] chave : int ) : DataRow

MoradaDAL

+ FindByID ( )

+ Update ( )

+ Delete ( )

+ Insert ( )

source: Microsoft Application Architecture Guide 2.0

Layers vs. Tiers43

fonte: Application Architecture for .NET: designing applications and Services

Part 4

Sample problem & Application

The problem: Revenue Recognition45

Contract

+ revenue

+ dateSigned

Product

+ name

Customer

+ name1

* 1

*

1

WordProcessor SpreadSheet

Contract

+ revenue

+ dateSigned

Product

+ name

Customer

+ name1

* 1

*

1

WordProcessor SpreadSheet

� 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)

RevenueRecognition

+ dateRecognition

+ amount

*

DataBase

RevenueRecognition

+ dateRecognition

+ amount

*

DataBase

Requirements46

� For a given contract, calculate when each revenue will happen and the amount due

� For a given contract, calculate how much revenue it � For a given contract, calculate how much revenue it has generated as of a certain date

Business interface

public interface IRevenueRecognition{

void CalculateRevenueRecognitions(int contractID);

Money RecognizedRevenue(int contractID, DateTime asOf);

47

object GetContracts();

object GetCustomers();

object GetProducts();}

Relational model

«table»

TRevenueRecognitions

+ «Column» ID : int

+ «Column» contractID : int

+ «Column» dateRecognition : date

+ «Column» amount : currency

«table»

TRevenueRecognitions

+ «Column» ID : int

+ «Column» contractID : int

+ «Column» dateRecognition : date

+ «Column» amount : currency

48

«table»

TContracts

+ «Column» ID : int

+ «Column» productID : int

+ «Column» customerID : int

+ «Column» revenue : currency

+ «Column» dateSigned : date

«table»

TCustomers

+ «Column» ID : int

+ «Column» name : varchar

«table»

TProducts

+ «Column» ID : int

+ «Column» type : varchar

+ «Column» name : varchar

+ «Column» amount : currency

«table»

TContracts

+ «Column» ID : int

+ «Column» productID : int

+ «Column» customerID : int

+ «Column» revenue : currency

+ «Column» dateSigned : date

«table»

TCustomers

+ «Column» ID : int

+ «Column» name : varchar

«table»

TProducts

+ «Column» ID : int

+ «Column» type : varchar

+ «Column» name : varchar

+ «Column» amount : currency

The workbench application

output

Architectural style

49

Business operations

http://w2ks.dei.isep.ipp.pt/psousa/GetFile.aspx?file=PoEAAWorkbench.zip

Remember the questions?

� The workbench will show

� How to represent the business entities

� How to persist its state

� How to code the Business logic

50

� How to code the Business logic

� How to guarantee data coherence

� The workbench will not show

� How to handle application distribution

The first big question51

Table-oriented

Versus

Object-oriented

Architectural examples

� Table oriented

� Table Module + Table Data Gateway (DataSet)

� Table Module + Table Data Gateway (Custom Classes)

52

� Object-oriented

� Domain Model + Active Record

� Domain Model + Data Mapper

Architectural examples

� Transaction Script using DataSet� Transaction Script� Transaction Script + Data Gateway

� Transaction Script using Custom Classes� Transaction Script

Transaction Script + Row Data Gateway

53

� Transaction Script + Row Data Gateway

� Table Module� Table Module + Table Data Gateway (DataSet)� Table Module + Table Data Gateway (Custom Classes)

� Domain Model� Domain Model + Active Record� Domain Model + Data Mapper

focus

Workbench’s architecture54

Different arch. Styles. These are the classes to “look” at

RevenueGUI RevenueFacade

Common

implementation

The RevenueFacade layer

� 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)

55

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

Factory56

� Problem:

� How to hide the details of object creation specially when there are special conditions on how and which object (interface implementation) to create?

Pattern

� 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

Factory57

� Provides a way to hide complexity of object creation

Pattern

Façade

� Problem:

� Actual work is performed by two or more objects, but you want to hide this level of complexity from the client.

Pattern GoF

� Solution:

� Create a facade object that receives the messages, but passes commands on to the workers for completion.

Façade

� 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.

Pattern GoF

59

source: Design Patterns: Elements of Reusable Object-Oriented Software

Singleton

� Problem:

� You want to ensure that there is never more than one instance of a given class.

Pattern GoF

� Solution:

� Make the constructor private, have a method that returns just one instance, which is held inside the class itself.

Singleton

� Ensure a class has only one instance and provide a global point of access to it.

Pattern GoF

61

soure: Design Patterns: Elements of Reusable Object-Oriented Software

DEMO62

Part 5

PoEAA Preview

Business entities

� Record Set versus Custom class

� One versus many

� Relationships (networks, hierarchies, etc.)

� XML

Table-oriented: Packages

UI UI

TM+TDG TM+TDG+CC

«table module»

BLL

«table data gateway»

DAL

Uses the plaform Record Set

«table module»

BLL

«table data gateway»

DAL

Entities

These classes have onlyattributes

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+ GetContractsByCustomer ( [in] customerID : int ) : DataSet

Customer

+ Customer ( )

+ GetCustomers ( ) : DataTable

Product

+ Product ( )

+ GetProducts ( ) : DataTable

One class per table

handles all the records in the

table

Table oriented: CalculateRevenues

/ ClassifierRole2 : Contract

Gateway

/ ClassifierRole1 : Contract/ GUI/ User : Actor1

1 : \btnCalcRevenues_Click\

2 : CalculateRevenueRecognitions (

contractID )

3 : \new\

4 : GetContractByID ( contractID ) 4 : GetContractByID ( contractID )

5 : BeginTransaction ( )

6 : InsertRecognition ( contractID ,

recognitionDate , amount )

7 : CommitTransaction ( )

foreach calculated

recognition

Object-oriented: Packages

GUI UI

DM+AR DM+DM

«domain model + active record»

BLL + DAL

«domain model»

BLL«data mapper»

DAL

Database

Object-oriented: Domain Model

Contract

+ «property» Product : Product

- _ID : int

- _CustomerID : int

- _DateSigned : DateTime

- _ProductID : int

- _Revenue : decimal

+ «property» Customer : Customer

+ «property» RevenueRecognitions : IList

+ «property» DateSigned : DateTime

+ «property» Revenue : decimal

+ «property» ID : int

Customer

- _ID : int

- _name : string

+ «property» ID : int

+ Customer ( )

+ «get» ID ( ) : int

- _Customer

Product

+ «property» Type : string

- _ID : int

True OO model; each object

handle one entity (“record”)

A Workbench for Learning Enterprise Patterns

+ «property» ID : int

~ AddRecognition ( [in] recognitionDate : DateTime , [in] amount : decimal )

+ Contract ( )

+ RecognizedRevenue ( [in] asOf : DateTime ) : Money

+ CalculateRevenueRecognitions ( )

+ «get» Product ( ) : Product

~ SetID ( [in] id : int )

~ SetProduct ( [in] prodID : int , [in] prodType : string )

- SetStrategy ( [in] prodType : string )

~ SetProduct ( [in] prodID : int )

+ «get» Customer ( ) : Customer

+ «get» RevenueRecognitions ( ) : IList

+ «get» DateSigned ( ) : DateTime

+ «get» Revenue ( ) : decimal

+ «get» ID ( ) : int

~ SetCustomer ( [in] custID : int )

+ «set» Product ( [in] value : Product )

+ «set» DateSigned ( [in] value : DateTime )

+ «set» Revenue ( [in] value : decimal )

- _ID : int

- _name : string

- _type : string

+ «property» ID : int

+ Product ( )

+ «get» Type ( ) : string

+ «get» ID ( ) : int

- _Product

RevenueRecognition

+ Amount : decimal

+ DateRecognition : DateTime

+ ID : int

+ RevenueRecognition ( [in] id : int , [in] dt : DateTime , [in] amt : decimal )

+ RevenueRecognition ( [in] dt : DateTime , [in] amt : decimal )

- _RevenueRecognitions*

IRevenueRecognitionStrategy

- theStrategy

Object-oriented: CalculateRevenues

: ContractMapper : Actor1 / UI : IRevenueRecognitionStrategy/ c : Contract : DBFactory

1 : \btnCalc_Click\

2 : CalculateRevenueRecognitions ( )

3 : CalculateRevenueRecognitions ( )

4 : AddRecognition ( recognitionDate ,

amount )

foreach recognized

A Workbench for Learning Enterprise Patterns

70

: IDBHelper

5 : Save ( c ) 6 : CreateDBHelper ( )

7 : \new\

8 : BeginTransaction ( )

9 : ExecuteTransactedNonQuery ( cmd

)

10 : ExecuteTransactedNonQuery (

cmd )

11 : CommitTransaction ( )

foreach recognized

revenue

foreach recognized revenue

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”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

Distributed applications72

contract

To conclude

Session synopsis74

� Introduced the concept of

� Enterprise application

� Software pattern

� Software architecture� Software architecture

� Layered architectures

� Presented the sample problem

� Presented an overview of the rest of the seminar

At this final stage [...] The patterns

aren’t important. The forces in the

problem domain and how to resolve problem domain and how to resolve

them are.

Christopher Alexander (1979)

Patterns of Enterprise Applications (by Example)

Paulo [email protected] http://linkedin.com/in/pagsousa 76

ISEP/IPP

REFERENCES

Bibliography78

� 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 � 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=/library/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

Bibliography79

� Domain logic and SQL. Martin Fowler. http://www.martinfowler.com/articles/dblogic.html

� Why extends is evil. Allen Holub http://www.javaworld.com/javaworld/jw-08-2003/jw-0801-toolbox.html2003/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/published.pdf

� Don’t live with Broken windowshttp://www.artima.com/intv/fixit.html

Pattern catalogs

� 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

80

� Core J2EE Patterns http://www.corej2eepatterns.com

� Enterprise Solution Patterns Using Microsoft .NET. http://msdn.microsoft.com/architecture/patterns/default.aspx?pull=/library/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=/library/en-us/dnpatterns/html/Dp.asp