Sa 03 1 Architecturalpatterns Modules
Sa 03 1 Architecturalpatterns Modules
Architectural patterns
Learning objectives
review the Layer, Onion, and the Aspect-Oriented pattern as examples of the most common
architectural patterns in the Module category
discuss the motivations for their use, the elements and constraints they consist of, and their
weaknesses and strengths
compare the so-called Cake pattern with injection frameworks for realising dependency
inversion
2
What is an architectural pattern?
Proceedings of the 21st International Computer Software and Applications Conference, 1997, pp. 6-13.
focus
Keywords: software architecture, architectural styles, style classification/taxonomy
Problem overview
Most software architecture documentation
(e.g., method calls, events, or message bus)
A topological layout of the components
tools’ utility has yet to be fully validated. Doc- describes the system’s structure from different
umenting architectural decisions thus remains views.1 Ideally, this documentation also records
difficult and we continue to lose important decisions that architects made while designing
information. the system. Recording only the decision does lit-
Architecture patterns address these docu- tle good, however; for the documentation to be
mentation challenges by capturing structural truly useful, architects must also capture the al-
and behavioral information and encouraging
architects to reflect on decisions in a way that
doesn’t interfere with the natural architectural
design process. Architecture patterns are easy
to use, giving developers a rich set of infor-
ternatives considered, their expected conse-
quences, and the rationale—that is, the reasons
for selecting a particular alternative. Our discus-
sion of decision documentation here refers not
just to the decision but rather to all of its as-
A set of semantic constraints covering topology,
element behavior, and interaction mechanisms
mation about rationale, consequences, and re- pects. Unfortunately, when architects document
lated decisions. Essentially, they offer reusable their decisions, this wider definition is what they
knowledge for the architect’s toolkit. Here, we most neglect.
38 IEEE SOFTWARE Published by the IEEE Computer Society 0740-7459/07/$25.00 © 2007 IEEE
3
3.1 Module Patterns
4
Layer Pattern
Figure 2.17
There may be three layers
here, but this is not a design A
in the layered style, which
forbids upward uses.
B
Key
x Layer
C Allowed to use
Context
Need to develop and evolve portions of complex software systems independently.
Problem
The software needs to be segmented in such a way that the modules can be developed
and evolved separately with little interaction among the parts,
supporting portability, modifiability, and reuse.
Solution
To achieve this separation of concerns, the layered pattern divides the software into units
called layers. Each layer is a grouping of modules that offers a cohesive set of services.
The usage (e.g., import type, invoke method) must be unidirectional. Layers completely
partition a set of software, and each partition is exposed through a public interface.
5
Layer Pattern Solution
Overview
The layered pattern defines layers (groupings of modules that offer a cohesive set of
services) and a unidirectional allowed-to-use relation among the layers.
Elements
Layer, a kind of module.
The description of a layer should define what modules the layer contains.
Relations
Allowed-to-use. The design should define what the layer usage rules are and any
allowable exceptions.
Constraints
Every piece of software is allocated to exactly one layer.
Layer n provides a set of services to layer n+1 and uses the services of layer n-1.
“Layer bridging” is sometimes allowed downwards, but should be avoided.
There is a clearly-defined and stable interface between adjacent layers,
of which only the implementation can change.
Strengths
Promotes modifiability, reuse, portability.
Achieves separation of concerns.
Manages complexity and facilitates communication of code structure to developers.
Weaknesses
The addition of layers adds up-front cost and complexity to a system.
Layers contribute a performance penalty. 6
kernel through system calls. The system call interface layer iso-
lates the kernel implementation details and provides a virtual
Layer Pattern Examples
Figure 2.26
user space
User programs
Unix System V
The primary presentation of
a layered view of the UNIX
System V operating system
implementation (adapted
from Bach 1986)
Libraries
kernel space
file subsystem process control subsystem
(ipc, scheduler, memory mgmt)
buffering
mechanism
“The diagram serves as a useful
logical view of the kernel,
character block I/O although in practice the kernel
device drivers device drivers deviates from the model because
some modules interact with the
internal operations of others.”
hardware control
[Bach 1986]
Key
User-level Kernel-level Allowed
layer layer to use
7
using
com.foo.proj.ui.dto
com.foo.proj.ui.act
com.foo.proj.ui.svl
Layer Pattern Examples
com.foo.proj.ui.ctl
com.foo.proj.pojo
com.foo.proj.dao
module
com.foo.proj.svc
com.foo.proj.dto
used
module
com.foo.proj.ui.svl 0 0 0 0 0 0 0 0
com.foo.proj.ui.act 0 0 0 0 0 0 0 0
com.foo.proj.ui.ctl 1 1 0 0 0 0 0 0
com.foo.proj.ui.dto 1 1 1 0 0 0 0 0
J2EE web applications com.foo.proj.svc 0 0 1 0 0 0 0 0
com.foo.proj.dao 0 0 0 0 1
0 0 0 0
2.4 Layered S
com.foo.proj.dto 1 1 1 0 1 1 0 0
data transfer objects: com.foo.proj.pojo 1 1 1 0 1 1 0 0
simple classes grouping data Figure 2.32
DSM for a layered design. The highlighted cells above and below the diagonal represent de
not allowed
Presentation
—J.S. and P.M.
action classes proj.ui.svl proj.ui.act
proj.pojo
com.foo.
proj.ui.ctl
e.g., CtlRetrievePaymentToDay
implements steps required for one use case Service classes com.foo.
proj.svc
com.foo.
proj.dto
e.g, SvcFulltimeEmployee
implements core business logic DAO classes com.foo.
associated with domain classes proj.dao
Layer
Allowed to use
8
Dependency Inversion: from Layer to Onion
9
Dependency Inversion: from Layer to Onion
Messagin
Presentation
outer layers depend on inner layers,
as they implement the interfaces declared there Domain
g
changes to outer layers do not affect inner layers, Model
the inner layers do not know about the outer layers
inner layers can be compiled, run, and tested
s t
Tes
separately from the infrastructure layers
RE
ST
(e.g., swap an outer layer for a mock
Persistence
when testing an inner layer)
10
Onion in Scala: Cook example
API
[Waldron, ScalaDays 2016]
11
API ring for Cook example: module declaration
trait DomainModule:
val cookRepository: CookRepository
val eggRepository: EggRepository
12
13
also known as
callback hell
trait DomainModule:
val cookRepository: CookRepository
val eggRepository: EggRepository
16
Domain ring for Cook example: module contents
trait CookRepository:
def findOne(): Future[Cook]
we might run
out of eggs
trait EggRepository:
def findAndRemove(): Future[Option[RawEgg]]
def add(egg: RawEgg): Future[Unit]
17
18
object EggStyle:
case object Scrambled extends EggStyle(3.minutes)
case object SunnySideUp extends EggStyle(3.minutes)
case object OverEasy extends EggStyle(4.minutes)
case object OverMedium extends EggStyle(5.minutes)
case object OverHard extends EggStyle(6.minutes)
case object HardBoiled extends EggStyle(6.minutes)
case object SoftBoiled extends EggStyle(3.minutes)
case object Poached extends EggStyle(5.minutes)
object Cook:
case object OutOfEggsException
extends IllegalStateException("There are no more eggs")
trait InfrastructureModule:
this: ApiModule with DomainModule =>
trait TestModule
extends DomainModule
with InfrastructureModule
with ApiModule:
23
high-level layer declares interface
implemented by low-level layer Infrastructure
coupling direction is inwards from outer low-
Alternatives for realising dependency inversion level layer (e.g., for persistence) to inner high-
level layer (e.g., for business logic)
API
Messagin
Presentation
outer layers depend on inner layers, as they
implement the interfaces declared there Domain
g
changes to outer layers do not affect inner Model
layers, the inner layers do not know about the
outer layers
s t
Tes
inner layers can be compiled, run, and tested
RE
ST
separately from the infrastructure layers (e.g.,
Persistence
swap an outer layer for a mock when testing
an inner layer)
Cook example implements the so-called “Cake pattern” for dependency inversion
9
Strengths
Realised solely through built-in language constructs such as self types
Module composition is checked for type-safety at compile-time
Weaknesses
[Oderski, OOPSLA05] Has earned the reputation of being difficult to understand
Easy to make mistakes in the implementation of the pattern
25
Separation of Concerns in Apache Tomcat
XML Parsing: one module (i.e., class)
26
Figure 2.36.
Crosscutting Concerns
code scattering
code
tangling
...
Account Customer Atm
Key
Code to handle access control
Class
Code to handle logging
code
Code to handle transaction management
Figure 2.36
Inappropriately modularising a crosscutting concerns leads to
The traditional object-oriented implementation of a bank automation system would have several classes where
Scattering:
the business logic itswith
is tangled implementation being
code that handles dispersed
crosscutting all oversuch
concerns, theasplace
access control, logging, and
transaction management.
Tangling: itsIn implementation
addition, the code being
that handles a particular
intertwined withcrosscutting concern is repeated
the implementation and
of others
scattered across several classes.
Problems related to comprehension and maintainability
27
Modularizing Cross-cutting Concerns 2.6 Data Model ■ 109
Classes with
business logic
code
. . .
Aspects that
modularize code
of crosscutting
concerns
Figure 2.37
Aspect-oriented programming provides programming constructs for factoring out cross-
In the aspect-oriented implementation of the same bank automation system, the classes don’t contain code for
logging, access control, transaction management, and other crosscutting concerns. The code to handle these
cutting concerns from modules into a separate module called an aspect that consists of:
concerns is now inside aspect modules. Classes such as Account, Customer and Atm contain the business logic
only. The AOP compiler will use the weaving process to insert the code inside aspects at the locations in the
classes where it’s needed.
Advice
contains the code for the cross-cutting concern
Pointcut expression
2.6 Data Model
specifies the join points in the base program where base and cross-cutting concerns
should
2.6.1 be composed
Overview
joinmodeling
Data points areis a specific
common to eachin AOP
activity language,
the software according to its join point model:
develop-
ment
e.g., process
method of information
invocation,systems.
method The execution,
output of thisinstance
activ- creation, error throwing, …
ity is the data model, which describes the static information 28
2.5 Aspects Style ■ 107
checkStatusAndCloseTransaction() ...
Crosscuts:
Crosscuts all public methods of —all public methods of all classes with suffix ServiceImpl
all classes with suffix ServiceImpl —the handleRequest() method of all classes that
AND any method with the implement Spring’s Controller interface
@transactional annotation —the run() method of all threads
«aspect» org.gwtwidgets.server.spring
«aspect» «use»
AuthorizationCheck
Enforcement
... ServletUtils
...
«use»
Compile-time declarations
to identify points in the code com.ikaru.ikewiki.user
that violate the layered Crosscuts any method
Key: UML
design or coding policies with the
Color used to enhance
«entity» @privilegedAccess
readability.
User annotation
... “. . .” indicates there are
other elements in the
package.
Aspect-oriented
Figure 2.35
J2EE application implemented using Spring and Google Web Toolkit.
• TransactionManagement
Primary aspect
presentation for the aspects ensures
view of requests
the IkeWiki received
application. This JavabyEEserver close
application databasewith
implemented
Spring framework and Google Web Toolkit uses aspects for some crosscutting concerns. The TransactionManagement
transactions,
the and
perform
aspect a transaction
makes sure all requestsrollback
received bywhen an exception
the server occurs. and release database resources properly,
will close the transaction
•performing a rollback when
ExceptionHandling an exception
aspect logs, occurs.
displays, The and
ExceptionHandling
notifies theaspect has code to log
administrator the error
of each to the
exception.
database, send e-mail notification if applicable, and wrap the exception with a proper user message to be displayed by
Woven into
threads
the and entryThispoints
client application. aspectto handlers
is woven for HTTPclasses
into server-side requests.
that are either threads or entry points to process
•HTTP requests. The AuthorizationCheck aspect is used to check if the current user has permission to execute a specific
AuthorizationCheck aspect performs access control on specific methods.
method. The Enforcement aspect is different from the others. It doesn’t exactly implement a crosscutting concern, but
• Enforcement
rather it scans the aspect
coding policies.
does
source code NOT implement
at compile time looking fora violations
cross-cutting concern.
of the layered design,Itaslooks
well asfor violations
violations of design
of several
invariants and coding conventions at compile-time. 29
Enterprise AOP with Spring Applications
SAMPLE CHAPTER
Ramnivas Laddad
FOREWORD BY ROD JOHNSON MANNING
d in
ool- Class_1.java
olkit
mat-
log
ime () Logger
am-
soci-
class
file
Class_n.java
Fig-
ven- ()
lo g
over
add-
eed
stru-
Figure 10.1 Conventional tracing, where all
the conventional logging
log points issue calls to the logger explicitly AOP-based logging
30
Enterprise AOP with Spring Applications
SAMPLE CHAPTER
Ramnivas Laddad
FOREWORD BY ROD JOHNSON MANNING
@Pointcut("execution(* *.*(..))")
public void traced() {
}
@Before("traced()")
public void trace(JoinPoint jp) {
Signature sig = jp.getSignature();
logger.log(Level.INFO, "Entering [" + sig.toShortString() + "]");
NDC.push(" "); pushes indentation on
} the logger’s “nested
diagnostic stack” (Log4J)
@After("traced()")
public void exit() {
NDC.pop();
}
}
trait Channel {
def send(x : String) = println(x)
} MASTERS THESIS
FREDRIK SKEEL LØKKE 20022555
Strengths
Modularizes cross-cutting concerns.
Supports comprehension and modifiability.
Weaknesses
Little language support.
Prone to the fragility problems: pointcuts and advice make many implicit
assumptions about the modules into which they cross-cut.
34