0% found this document useful (0 votes)
4 views97 pages

3 DesignPrinciplesEN

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views97 pages

3 DesignPrinciplesEN

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 97

Patterns and standards of data access

Information Repositories

School of Computer Science

2024-2025
Car WorkShop - The initial project

2 of 97
Car workshop use cases

3 of 97
Car workshop domain model

4 of 97
Car workshop Table model

5 of 97
CWS0 package structure

By actors: Each
package contains
text menus and
subpackage (action)
implementing menu
options.

6 of 97
Mechanics Management class diagram
CWS0 implementation

Return to 26
7 of 97
Add mechanic sequence diagram
CWS0 implementation

8 of 97
Cashier class diagram
CWS0 implementation

Return to 28
9 of 97
Create invoice sequence diagram
CWS0 implementation

■ User interaction, data


validation
■ Business logic code
■ Data access code
■ Messy: All together in the
same class

10 of 97
WorkOrdersBillingAction::execute()
CWS0 implementation

11 of 97
Quality standards

12 of 97
Software system quality attributes

■ Scalability As the system grows (in data volume, traffic volume, or


complexity), there should be reasonable ways of dealing with that
growth. Music, Book, Software vs Hairdressing

■ Maintainability are the relative costs of fixing, updating,


extending ... over its lifetime Operating system updates

■ Reusability is the ability of software elements to serve for the


construction of many different applications. Libraries of generic
(Math), high-level programming languages, widgets, ...

■ Extensibility The ease of adapting software to changes of


specification. Modular kitchen carpenter-made kitchen

13 of 97
CWS0 evaluation
Poor Maintainability
■ Changing persistence, UI, . . . means changing (almost) every class.
■ Repeated code has a big impact in maintainability
Poor extensibility
■ With tangled code, adding a new behaviour (encrypt data) makes
you worrying about how it affects the features around it
Poor Reusability
■ Reuse data access code into some other application is impossible.
Poor scalability
■ Trying to optimize database access (connection pooling) means
changing everything
14 of 97
Action classes implement all concerns: user interaction + logic +
data access
No separation of concerns
■ Code corresponding to a concern is not well encapsulated in a
module, and ends up being scattered across many modules.
■ It is difficult to locate and understand the implementation of a
concern because it is tangled with code that implements others.
■ Code is repeated everywhere it is needed (access to an specific
table).
The key to creating quality code is adhering to low coupling, high
cohesion principle.
■ Coupling assesses how tightly a module is related to others.
■ Cohesion refers to how closely the functions in a module are
related. Single responsibility (no schizophrenic classes)

15 of 97
Patterns

16 of 97
Common to most enterprise applications

■ Complex business logic Made up of individual components doing


something specific (payroll, invoicing, customer list, . . . )
■ Involve persistent data
■ Data-intensive systems
■ Concurrect access to data
■ Lot of user interface screens
■ Need to integrate with other entreprise applications scattered
around the enterprise
Due to these similarities, some patterns have appeared to ease
development
17 of 97
Patterns

A pattern describes a problem which 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 (building architect)

Design patterns are descriptions of communicating objects and classes


that are customized to solve a general design problem in a particular
context

Erich Gamma, Richard Helm, Ralph Johnson, John Vlissides

Highly recommended: VideoPattern


18 of 97
Software architectural pattern: Layered pattern

19 of 97
Reference architecture
■ Components are organized into layers.
■ Each layer exposes an interface (API) to be used by the layer
above it (object calls are all inward)
■ Each layer acts as a
□ Server: service provider to layer “above”
□ Client: service consumer of the layer “below”

■ User interface layer handles interaction


between client and business layer
(user-friendly I/O, requests to business, . . . )
■ Business layer encodes the real-world
business rules that determine how data can
be created, stored, and changed.
■ Data access interacts with persistent data
20 of 97
Advantages

■ Once a layer is built, it can be used for many higher-level clients


(reuse).

■ A single layer can be understood as a coherent whole without


knowing much about other layers (cohesion).

■ As long as interface is preserved, layers are unaware of changes in


the implementation of other layers (maintainability)

21 of 97
Downsides
■ Not universally applicable (transactions)
■ Extra layers can harm performance.
■ Layered architecture demands that dependencies run only one way
□ What happens if you want to change entity Account (change account
number to IBAN, support custodian data, ...). You will very likely
have changes in all layers.
□ Poor maintainability

It should only be applied at a


relatively small granularity.

22 of 97
Apply layered architecture to CWS0

■ Split application in two main layers (some operations will change


deeply)
□ Presentation layer: input (including input validations) + output
□ Business layer: Logic + Persistence

Each layer knows only adjacent layers (import higher layer,


import lower layer).
Each layer supports higher layer and is supported by lower layer.
Object calls are all one direction.
■ To pass arguments use Data Transfer Objects aka DTO
1
1
In the following UML diagrams, there could be some typo mistakes related to
package, classes or method names.
23 of 97
Package organization

■ UI. Classes ui.***.action implement


user interaction, do some input data
validations and invoke business classes.
■ Business. At this stage, business logic +
persistence. Package organized in
subpackages, in general, by use case,
although some complex use cases may be
organized by entity (billing).

24 of 97
Classes in the business layer

■ Business classes
implement business rules
(AddMechanic,
ListMechanics, . . . )
■ All of them look similar

25 of 97
Mechanics Management (CRUD) class diagram

Compare
with 7

26 of 97
Mechanics Management (CRUD) sequence diagram
User interaction code clearly separated from business and data access code

27 of 97
Workorder billing

■ Draw a class diagram for Cashier with separation of concerns


(Presentation – Business (+persistence))
Go to 9
■ Draw a sequence diagram for use case Workorder billing (create
an invoice for one or more workorders)
Goal : Split code in different layers

28 of 97
CWS V1: Layering
Cashier class diagram

29 of 97
CWS V1: Layering
Workorder billing sequence diagram

30 of 97
Façade Pattern

31 of 97
Remaining problems

■ Presentation layer depends on implementation classes on business


layer: Tight coupling
□ Classes in UI are responsible for creating objects and for invoking
methods in implementation classes in business
□ Changing implementation of such classes in business layer usually
means changes in classes in presentation layer and viceversa
■ Sometimes, classes in presentation layer refer to many
different in business layer with different interfaces, which makes
these classes hard to implement, change, test and reuse. For
example, PayOffInvoice

32 of 97
Context

It is a software-design pattern analogous to a facade in architecture


It is an object that serves as a front-facing
interface masking more complex underlying or
structural code.
■ Provides one simplified interface to an
otherwise difficult to use subsystem that is
good enough for most clients
■ Clients interact subsystem via Facade but
does not prevent access to subsystem
classes.
■ Could be more than one interface for the
same subsystem

33 of 97
Applicability
Reduce coupling between subsystems and clients and subsystems
themselves; could be strong within subsystem
public class Client public class Client
{ {
public void method ( ) { public void method ( ) {
Subsy stemClas s sc = new Facade ().
new Subsyst emClass (); c al lD oS o me th in g ();
sc . doSomething (); }
} }
}

34 of 97
A thin facade also hides the details of the interface. It is possible to
change implementation of subsystem in the future, while still
providing consistent functionality through a stable interface
public class Client
{
public void method ( ) {
Scanner s = new Scanner ();
Parser p = new Parser ();

s . scan ();
p . parse ();
}
}

public class Client


{
public void method ( ) {
new Compiler ().
compile ();
}
}

35 of 97
Class diagram

■ IFacade: Provides a high-level interface for hiding the complexity


of interacting with multiple systems to carry out an operation.
■ Client: System or event which interacts with the facade.

■ DefaultFacadeImpl:
Represents the implementation
of IFacade, which is in charge
of communicating with all the
subsystems.
■ Subsystems: Represents all the
modules or subsystems with
interfaces for communication.

36 of 97
Mechanics Management Facade

■ Create an interface (XXXService) per


use case.
■ Implement interface
(XXXServiceImpl)

37 of 97
Mechanics Management (CRUD) class diagram
Facade pattern

38 of 97
Add mechanic sequence diagram
Facade pattern

39 of 97
Workorder billing
Facade pattern

■ Draw a class diagram for Cashier subsystem with a façade


■ Draw a sequence diagram for use case Workorder billing (create
an invoice for one or more workorder)

40 of 97
Cashier class diagram
Facade pattern

41 of 97
Workorder billing sequence diagram
Facade pattern

42 of 97
Simple Factory (or Class Factory)

43 of 97
Remaining problems

There is still a coupling between user interaction layer and


business layer. These lines of code
M ec ha ni c Se rv ic e s = new M e c h a n i c S e r v i c e I m p l ( );
s . addMechanic ();

are no less tightly coupled than these ones:


AddMechanic m = new AddMechanic ();
m . addMechanic ();

■ UI classes depend on business classes implementation because


***Action classes need to know which is the class implementing
the façade to create an instance
■ Changing this class means changing presentation classes
Simple Factory pattern avoid this kind of dependencies [6]

44 of 97
Simple Factory Pattern

A Simple factory is a class that creates objects without exposing


instantiation logic to the client.
The create methods are often declared statically.

45 of 97
Class diagram

46 of 97
Simple Factory advantages

■ If an instance of a class is needed, client asks the factory to create


one so it knows nothing about implementation classes appart from
the factory and the class interface.

■ Changing the implementation of the class doesn’t mean changes in


the client (presentation layer).

■ Finally, factory can be adapted without changing its interface (only


changing the getXXXService() implementation).

47 of 97
Mechanics Management package structure
Class factory

2. UI requests a service (forXXXService) from


BusinessFactory
3. BusinessFactory returns class implementing
service interface (XXXServiceImpl).
4. UI classes depend on BusinessFactory and
services’ interfaces (XXXService); not on
implementation classes on lower layer.

48 of 97
Mechanics Management class diagram
Class factory

■ BusinessFactory
returns façade.
■ Changing service
implementation
means a change in
a method
forXXXService;
nothing else.

49 of 97
Add mechanic sequence diagram
Class factory

50 of 97
Workorder billing
Class factory

■ Draw a class diagram for Invoice subsystem with a façade


■ Draw a sequence diagram for use case Workorder billing (create
an invoice for one or more workorder)

51 of 97
Cashier class diagram
Factory pattern

52 of 97
Workorder billing sequence diagram
Factory pattern

53 of 97
Split business layer into business and data access
layers

54 of 97
Problems with data access from OO programs

Code that depends on specific features of data resources ties together


business logic with data access logic (coupling).
public MechanicDto execute () throws B u s i n e s s E x c e p t i o n {
...
c = DriverManager . getConnection ( URL , USERNAME , PASSWORD );
pst = c . p r ep a r e S t a t e m e n t ( SQL );
pst . setString (1 , mechanic . id );
pst . setString (2 , mechanic . dni );
...
pst . executeUpdate ();
...
}

■ Such code dependencies in components make it difficult to


migrate the application from one type of data source to another

55 of 97
Split into business and access layers

Split business layer into business layer and data access layer.

Patterns helpful for Data Access Layer


■ DAO pattern (Java BluePrints) [7]
■ Table Data Gateway (Fowler).

Patterns helpful for Business Layer


■ Service layer
■ Transaction scripts
■ Command

56 of 97
DAO (Data Access Object) Pattern

Design pattern to abstract and encapsulate all code needed to


persist data from classes in business layer to persistent storage and
viceversa, into a separate layer (DAL).

Data Access Objects (DAO) provides an OO generic API[9] to


access data stored in different DBMS

57 of 97
■ They hide all complex details involved in performing CRUD
operations in the underlying storage
■ Business objects use a simpler interface exposed by DAO.

58 of 97
Advantages of using DAO pattern

Decouples the persistent storage implementation from the rest of the


application
Decouples a data resource’s client interface (create, reads, update,
delete) from its data access mechanisms (JDBC, Spring JDBC, ...)
1. Business layer doesn’t have to know where data comes from,
even changing persistence mechanism. Shifting MySQL to
MongoDB, all changes are needed to be done in DAL only.
2. Persistence logic is completely separate, so is much easier to
write Unit tests for individual components. For example, using
JUnit, it will be easy to test individual components of application.
3. Data access mechanism can change independently of the code that
uses the data
59 of 97
Class diagram

Client Business object requires access to data source to obtain and


store data.
DataAccessObject DAO abstracts the underlying data access
implementation for the Business Object to enable transparent access
to the data source.
DataSource represents
a data source
implementation.
ResultSet represents
the results of a query
execution
Data Transfer Object
used as a data carrier

60 of 97
Example

61 of 97
Participants and responsabilities

Try CRUD Mechanics

62 of 97
DAO related patterns

DAO is a general and complex pattern and there are a number of


patterns related.

Martin Fowler, Patterns of Enterprise Application Architecture


http://martinfowler.com/eaaCatalog/index.html

Anyway, a Gateway is an object that encapsulates access to an


external system or resource[12].

63 of 97
Row Data Gateway
■ A Row Data Gateway object [11] acts as a gateway to a single
record in a data source.
□ Mimics exactly a single row returned by a query.
□ Each table column is a field in the object
□ Do not have domain logic
□ Finder object
■ https://www.sourcecodeexamples.net/2018/04/
row-data-gateway.html

64 of 97
Table Data Gateway
■ A Table Data Gateway object acts as a Gateway to a database
table or view.
□ One gateway for each table
□ Simple interface to a table with several find methods and methods to
maintain data
□ CRUD methods for accessing a single table or view
□ Finders return Collection of DTOs
■ An example in https://www.sourcecodeexamples.net/2018/
04/table-data-gateway.html

65 of 97
Read the page with DeleteMechanic.java business class and the
underlying database
■ Which DAO or TDG are necessary?
■ Which methods are needed in the TDG to abstract
DeleteMechanic from the storage?
■ Write the TDG (only methods identified above)
■ Rewrite business object using TDG
Problems detected (identify the line of code)

66 of 97
Where to get DAO from?

Frequently, several DAOs are needed (ClientDAO, VehicleDAO, . . . )

■ Automatic DAO Code Generation Strategy

■ Consider using some factory pattern to increase flexibility


1. Abstract Factory
2. Factory Method
3. Class Factory or Simple Factory: Preferred option

67 of 97
DAO and Abstract Factory pattern
When the underlying storage is subject to change from one
implementation to another.

68 of 97
DAO and Factory Method pattern
The underlying storage is not subject to change from one
implementation to another, use the Factory Method pattern to
produce a number of DAOs needed by the application.

69 of 97
Simple Factory

■ Draw UML diagram for Mechanic Management use case for BL


and DAL only
■ Rewrite business object DeleteMechanic
■ Write a simple factory for DAL

70 of 97
Split business into business and persistence:
Business

71 of 97
Business layer
Business logic encodes the real-world business rules that determine
how data can be created, stored, and changed.
It is not concerned with managing database (Data access layer) or
diplaying user interface (interface layer)
Business Layer defines application’s boundary and the set of
available operations from the perspective of interfacing client layers.

72 of 97
Business layer patterns

How can we organize the logic within the business layer?

There are three main patterns:

■ Transaction Scripts are the simplest way to organize domain logic


■ Domain Model
■ Table Module

We might also use Service Layer pattern on top of the domain


model.

73 of 97
Transaction scripts

Transaction Script organizes business logic by procedures where each


procedure handles a single request from the presentation.

■ Takes input data from the presentation layer,

■ processes the data with validations and calculations,

■ accesses data layer (or invokes operations from other systems)


through DAOs that encapsulate db access logic.

■ Replies to the presentation layer (Data Transfer Object pattern


is used to retrieve data from data layer and then to the UI layer).

74 of 97
Class diagram

Scripts should be in classes either


■ each script is a procedure; related scripts are enclosed in one class
■ each script is in one class (usually using the Command pattern)

Each invocation of a transaction script is transactional

75 of 97
Advantages and downsides

Advantages:
■ It is an ideal solution for systems with only a small amount of logic.
■ Simple, procedural model easy to understand.
■ It has little performance overhead
■ It performs well with simple data source layer when put into action
with patterns such as Row Data Gateway or Table Data Gateway.
Disadvantages:
■ Duplication of code in transactions.
■ Not suitable when domain model is complex

76 of 97
Domain Model pattern

It provides an object-oriented way of dealing with complicated logic.

Not one TS that handles all business logic for a user action

Several classes, each of them handles a slice of domain logic with both
the data, attributes, and all the behaviour that is related to that data.

Domain Model objects are usually in a one-to-one relationship with


records in database tables.

77 of 97
Exercises

■ Think on the Mechanic Management use case


■ Name the Transaction Scripts needed and several public and
private methods
■ Name classes needed in the Domain Model pattern. Write down
methods (public and private) you would need.
■ Now, imagine a TMechanics with 10 rows. How many instances of
each TS are there? And how many Domain Model objects?

78 of 97
Command Pattern
It intends to encapsulate complex operations for doing something (for
example, manage menus), in a single object.
So, instead of

Take in mind
that every menu
will repeat more
or less the same
structure (and
code)

79 of 97
80 of 97
Command Pattern
User interface with menus tried an approach to the Command
pattern (Gof) (also known as Action / Transaction)
■ Encapsulate requests as objects:
AddMechanicAction,
ListMechanicsAction, . . .
■ Menu issues requests without knowing
anything about operations requested or
receiver objects of the requests
Advantages
■ It decouples the classes that invoke the operation from the object
that knows how to execute the operation (AddMechanic in CWS1)
■ Extensibility Adding a new command can be done almost without
changing the existing code
81 of 97
Business implementation classes

82 of 97
83 of 97
Implementation

84 of 97
SL.TS.TDG

Let’s improve implementation


■ Presentation layer User interaction
■ Service Layer(SL) Entry point from view layer to business layer
■ Transaction scripts(TS) Application layer. One package per use
case. One class per transaction from view layer
■ Table Data Gateway (TDG) Responsible for persistence. One class
per table.

85 of 97
SL.TS.TDG 0

■ New persistence package


■ Gateway: Interface and implementation for every table
□ Move data access code from business objects (TS) to gateway objects
in this new package
□ TS contains only application code
□ AddMechanic (Transaction Script): Check that another mechanic with
the same DNI exists.
□ Gateway: Add the new mechanic to the DB; return mechanic by dni
■ Add a new persistence factory

86 of 97
SL.TS.TDG 0

1. Presentation layer (package


ui.XXX.action)
2. uses services factory to access
implementation service
3. Implementation service is done
in (Service Layer, package
business).

87 of 97
SL.TS.TDG 0

1. When Service Layer facade


(**ServiceImpl) receives a request,
2. it will address the request to
appropriate class (Transaction Script,
package
business.**.crud.commands).
3. The transaction script class will
implement logic actions and it will
address the request to the classes
responsible for persistence
(***GatewayImpl)
4. A persistence factory will be used to
get the appropriate classes
88 of 97
SL.TS.TDG 0
CRUD Mechanic. Class diagram

Notice layers
■ Presentation
■ Business
■ Persistence
Factories make decoupling a layer and its inmediate lower layer, easy

89 of 97
SL.TS.TDG 0
CRUD Mechanic. Sequence diagram

90 of 97
SL.TS.TDG 0
Invoicing

1. Invoicing class diagram


2. Create invoice sequence diagram (3 steps)
2.1 Presentation + SL + TS
2.2 SL + TS + TDG
2.3 TS + TDG. Explain data access.

91 of 97
Invoicing. Step 1: View + SL + TS

92 of 97
Invoicing. Step 2: SL+TS+TDG

Methods as updateBreakdown,
. . . , are not detailed. They use
gateways to access data.
Transactions are controlled in
execute()

93 of 97
Invoicing. Step 3: TS+TDG

Connect database detailed (as an


example).
■ It uses gateways to access
invoices and breakdowns data.
■ Gateways are requested to and
provided by a factory.
■ It sets autocommit (to control
transaction) and also sets
conections for the gateways
(consider using
getThreadConnection instead).

94 of 97
Further Reading (1)

[1] https://www.youtube.com/watch?v=8Zoz2njk5f8
[2]
https://www.oreilly.com/library/view/software-architectu
[3] https://javadevguy.wordpress.com/2019/01/06/
reevaluating-the-layered-architecture/
[4] https://martinfowler.com/bliki/
PresentationDomainDataLayering.html
[5] https://refactoring.guru/design-patterns/façade
[6]
https://javajee.com/factory-design-patterns-simple-facto

95 of 97
Further Reading (2)

[7]
https://www.oracle.com/java/technologies/data-access-obj
[8]
https://www.martinfowler.com/eaaCatalog/tableDataGateway
[9] https://www.oracle.com/technetwork/java/
dataaccessobject-138824.html
[10] https://martinfowler.com/eaaCatalog/gateway.html
[11] https://www.sourcecodeexamples.net/2018/04/
row-data-gateway.html
[12] https://martinfowler.com/eaaCatalog/gateway.html

96 of 97
Further Reading (3)

[13] http://what-when-how.com/Tutorial/topic-263rdl/
POJOs-in-Action-Developing-Enterprise-
Applications-with-Lightweight-Frameworks-352.html

97 of 97

You might also like