Course 5 – November 3 2020 Adrian Iftene adiftene@info.uaic.ro
Recapitulation course 4
◦ Business Process Modeling Notation
◦ Aspect Oriented Programming
Domain-Driven Design
◦ What Is DDD
◦ The Ubiquitous Language
◦ Model-Driven Design
◦ Refactoring Toward Deeper Insight
◦ Preserving Model Integrity
◦ DDD Patterns
AOP
Business Process Modeling Notation – offers a standard notation that is readily understandable by business
analysts, technical developers, business managers
AOP is a programming paradigm which isolates secondary or supporting functions from the main program’s business logic
AOP increases modularity by allowing the separation of cross-cutting concerns
Cross-cutting concerns - aspects of a program which affect other concerns
Advice - additional code
Pointcut - point where additional code is executed
Aspect - the combination of the pointcut and the advice
It is a way of thinking and a set of
priorities, aimed at accelerating software projects that have to deal with
complicated domains
A Model driven software design approach used to tackle the complexity of software projects
Collection of principles and patterns that
help developers craft elegant systems
Domain - A sphere of knowledge or
activity. What an organization does and the world it does it in
Model - A system of abstractions that describes selected aspects of a domain and ignores extraneous detail. Explains a complex domain in a simple way
A model is a distilled form of domain
Set of driving principles
Speak a Ubiquitous Language within an explicitly Bounded Context
Focus on the Core Domain, on the Object Model and on OO Design
Developers are also responsible for the model
A language structured around the domain model and used by all team members
Nouns == Classes
Verbs == methods, services, etc.
Example: A Hiring Specialist may post Jobs to the Job Board
◦ Classes = Job, JobBoard
◦ Actions = JobBoard.PostJob(Job)
It is used in:
◦ Speech
◦ Documentation
One of many integration patterns
◦ Continuous Integration
◦ Shared Kernel
◦ Customer / Supplier
◦ Conformist
◦ Anticorruption Layer
◦ Separate Ways
More than One Ubiquitous Language
◦ Applicant/Hiring Specialist/Department terminology
◦ Sales/Support terminology
Helps us solve specific problems in our domain
Is not necessarily “realistic”
Forms the basis of a language
Should remain current
The model can be expressed through class diagrams, explanatory diagrams, sequence diagrams or …
But, the design document is not the model!
Why is this important?
◦ Model-driven, not data-driven
◦ Focus on the domain, not the data structure
◦ Quickly swap out repositories for testing, POC, etc.
How?
◦ Plain Old CLR Objects (POCO)
◦ Repository pattern (abstract the data access)
◦ Aggregate Roots
“Refactor to deeper insights”
Include your domain experts in your refactoring
Refactor your ubiquitous language 1st, your code 2nd
This doesn’t mean refactor for greater reusability
Example: benefit disbursements
◦ Initially used Retro disbursements for final partial-month payments
◦ Realized that these required different actions
◦ Symptom: confusion around the name Retro when talking about
◦ Final Partial Payments
Origins – Eiffel language
Use for Distributed architectures
Move from class method level to the architectural level
Separate Bounded Contexts for reading and writing
◦ Write == Commands == Change state and return nothing
◦ Read == Queries == Pure functions that do not change state
◦ Optimize each side differently
Focus on:
◦ Event-Driven Architecture with Domain Events
◦ State Machines
Allows easy transitions to:
◦ Messaging services
◦ Asynchronous processing
◦ Massive scalability
Now! (Not really)
Fits approximately 5% of development project needs
DDD is a software methodology suited to a particular kind of application – one where
there is significant complexity, and there is a
significant focus on a well defined business
model. - Jak Charlton, Domain Driven Design
Step-by-Step
Entities
Value Objects
Aggregate Roots
Object Creation Patterns
Repository
Specification
Domain Services
Modules
Domain Events
State Machines
Objects which have an identity which remains the same throughout the states of the software
Behavior is the only criterion we use to differentiate among objects. - Dr. David West, Object Thinking
The Domain Model pattern:
◦ Structure
◦ Behavior
◦ No persistence behavior (i.e. Active Record)
Uniquely identified and tracked
Associated with other objects
◦ Simplify
◦ Remove unnecessary associations
Example: Bank Account for Jim Smith
Value Objects are the “things” within your model that have no uniqueness
Nothing special (no identity)
Don’t confuse with value type
Immutable
One instance can be used for in multiple entities
Examples:
◦ Money
◦ Address (usually)
◦ Codes
An aggregate is a cluster of Entities and Value
objects. (Object Graph) Each aggregate is treated as one single unit
Each Aggregate has one root entity know as the Aggregate Root
The root identity is global, the identities of entities inside are local.
Examples:
◦ Job Board (Job)
◦ Job (Skill, Applicant)
◦ Applicant (Applicant Skill)
Aid in object creation
Entities and Value Objects should ALWAYS be valid!
Constructors
Factory
◦ Simple Factory (Factory Method moved up to its own class)
◦ Factory Method (static method)
◦ Abstract Factory (composes from parts via inheritance)
Builder
◦ Fluent Interfaces
◦ Example: String Builder
Other Gang of Four patterns
Abstraction over data access
Acts as a collection of Aggregate Roots
Various approaches:
◦ Repository per Aggregate (very explicit)
◦ Generic Repository
◦ Repository per aggregate built upon Generic Repository Strategy
◦ Generic Repository with Specifications
Used for querying and adding/removing
◦ Some implementations also add an Update
◦ Generally used along with a Unit of Work (e.g. DataContext)
Simple interface for defining criteria:
◦ IsSatisfiedBy(T entity)
◦ Similar to the Query Object pattern
Very intention revealing
Very easy to test
Easy to chain together for more complex queries:
◦ CompositeSpecification: And, Or, Not
◦ LINQPad uses PredicateBuilder for a similar effect
A Domain Service is Business Logic in the domain that are not a natural part of an Entity or Value Object
Do not confuse with Application Services
Defining characteristics:
◦ Actions that do not fit within an entity or aggregate
◦ Stateless
Examples:
◦ Transfers
◦ Calculators
Break up your domain to reduce complexity
Becomes part of the ubiquitous language
High cohesion within module, loose coupling between modules
Helps with decoupling
Aids in extensibility
These are not delegate events
Domain Models (Aggregates) publish events instead of saving to the database
Eventual consistency (just like every other model)
In Command Query Separation (CQS), you don’t change state, you publish changes
State Machines: transition from one state to another
Domain Model (Aggregate) defines transitions
Examples:
◦ HTTP
◦ Stateless
Useful for very difficult and complex domains
Can help identify requirements
Focus on the language
Feel free to use patterns in other styles
Add Command Query Separation for
distributed systems
AOP is a new programming technique for
modularizing behavior that cuts across many classes
AOP is a technique for making programs more
modular by identifying and separating “cross-cutting concerns”
A concern is a feature point, or a requirement
A crosscutting concern is a concern that needs to be applied in many different compilation modules (In Java, this means we are talking about a requirement that touches many different classes)
“All exceptions must be logged”
“Capture all sql statements produced by the application”
“Cache all data that is rarely changed”
“Record all changes to the account for historical purposes”
“Timing, authentication, and persistence”
Solution without AOP: implementation in many different classes (‘code-scattering’ or ‘tangling’ => code that is difficult to change)
OOP is a paradigm for analysis design and development
AOP is not a replacement for OOP. It is a tool to help deal with some of the problems inherent in OOP
Aspects are in some ways like Dynamic Proxies, XDoclet, EJB/JSP containers, and CLR (& JSR 201) meta-data
All are trying to remove redundant code, make it possible to supply additional behavior at runtime to objects that is declaratively proposed and interjected at runtime
Separate concerns
Provide a way via language and runtime to describe crosscuts
How does it work?
◦ Write the classes
◦ Write the aspects
◦ Weave together
When do you weave?
◦ When you weave is implementation dependent
◦ AspectJ 1.0 did it at compile time (meaning that you needed the source for the code you wanted to weave.)
◦ AspectJ 1.1 uses a bytecode weaver, so classes without source can be woven
◦ In reality it could be done at compile time, link time (1.1), load
Tracing
Log sql
Good coding practice (sql access)
Log errors, serialize, produce junit
dbc (no return null)
Caching
Exception cleanup
Who called ctx.setRollBackOnly();
Logging & Exception Handling
Debugging
Profiling and performance monitoring
Testing
An open source language (initiated by Gregor Kiczales group)
Initial at Xerox, now at Eclipse
100 % Java compatible and add new extensions
AOP implementation
Current version is 1.9.6, 22.07.2020
The AspectJ
TMProgramming Guide:
http://www.eclipse.org/aspectj/doc/released/
progguide/index.html
Download from eclipse.org/aspectj
Run executable JAR
Use aspectjrt.jar on CLASSPATH
Or, use Eclipse and AJDT plugins
Or, use Netbeans and AJDT plugins
Or, use C#
Concern - a feature point, or requirement
Crosscutting concern - a feature point that cannot be encapsulated in one class
Aspect - the code for new functionality
Join Points - a specific point in the execution of the
program (method calls, constructor invocations, exception handlers)
Pointcuts - a structure and syntax for selecting join points
Advice - code to be executed when a join point is reached
Introductions (Inter-type declaration) - the ability of aspect oriented programs to alter existing program
structure (adding members to existing classes, adding methods, etc.)
Write the component
Write the aspect
In the aspect, first write the pointcut, then the corresponding advice
Compile with the ajc compiler, using the aspectjrt.jar file on the classpath for compile
Run with aspectjrt.jar
The pointcut (which selects the joinpoints, and the advice) are packaged into the compilation unit, the aspect. Aspects can be named with aj extensions, or
aspect
pointcut
before in
Method call
◦ Join point is within the calling application
pointcut foo() : call( public void setName(String) ) && target(Student);
◦ defines a pointcut as a call from any object of static method to a method;setName as long as the target of the call is of type Student
Constructor call
◦ Join point is within calling object
pointcut const() : initialization (Student.new() );
Method call execution
◦ Join point is within the called method, before any code is executed pointcut inFoo() : execution( public void setName(String) );
Constructor call execution - Within constructor body, before statements
Field get - When a field is referenced
Field set - When a field is changed
Exception handler execution - When an exception handler is executed
Class initialization - When static intializers are executed
Object initialization - Just before return of object constructor
Names can be matched with ‘*’, parameters with ‘..’
◦ call (* * Student.* (*)) matches all method calls on Student (regardless of visibility or return type) with one argument
◦ call (* * . (*)) matches all method calls with 1 parameter
◦ call (* * . (..)) matches all method calls
Subtypes can be matched with ‘+’
◦ call (* * Student+.* (*))
Can also match on throws patterns
◦ call (public void Student+(. .) throws Exception+)
Watch out for infinite recursion ! - Aspects match
Problem: we want to know when something changes the student (name or grade)
Solution: we add a pointcut for all “set” methods
Problem: we want to trace our program execution
Solution: we add a pointcut for all methods
set println
pointcut name([parameters]): designator(ajoinpoint);
the name will be used to handle actions when a join point is encountered
the ajoinpoint is a signature match
the designator decides when this particular join point will match (e.g. on method call)
pointcuts can be combined with logical operators
&&, ||, !
Problem: we want to follow methods setName or setGrade
Solution: we add a pointcut for both methods
pointcut name([parameters]): designator(ajoinpoint);
execution - method execution
call - call to method
initialization - first constructor
handler - exception
get - field access
set - field write
this - returns the object associated with a join point, or limits the scope
args - exposes the arguments to join point, or limits the scope
target - returns the target object, or limits the scope
cflow - join points in the execution flow of another join point
cflowbelow - join points in the execution flow of another join point, excluding the current
staticinitialization - static init
withincode - join points within a method or constructor
within - match with a type
if - dynamic condition
adviceexecution - match advice join points
preinitialization - preinit
Use when you are interested in the invocation of a method
Control is still in calling object , use execution() for control in called object
call (public void Student.setName(String));
The second half of AOP
Advice is what gets executed when a join point is matched
Advice is always relative to a joinpoint
type ([parameters]) : joinpointid (param list) { … }
Type can be: before, after and around
before - excellent for preconditions argument checking, setup code, lazy init
before() : pointcut { advice }
after - can be qualified with: after returning (if join point computation concludes successfully), or after throwing (if join point computation throws an exception). Cleanup of resources, checking/manipulating the return value
after() returning() : pointcut { advice } after() throwing() : pointcut { advice } after() : pointcut { advice }
around - the most powerful advice can replace
invocation, or just surround use proceed() to call method around() returns type : pointcut { advice }
◦ return type widening
◦ advice must return a value
◦ advice must explicitly act to proceed with join point computation if the computation is to continue at all
Because the flow of control dips through the advice, it can modify method arguments and/or the return value
Implements a middle wrapping layer that is completely
If more than one advice block affects the same join point, they operate in this order:
around advice is run most specific first
before advice is run most specific first
after advice is run least specific first
Of course, if any around advice executes that does not continue with join point computation, no other advice runs for the join point
Can be used to expose object to advice, or narrow pointcut selection
this (class type pattern, or id)
target(class type pattern, or id)
args(class type pattern, or id)
info about the join point that was just matched from inside the advice
◦ the kind of join point (call, execution, …)
◦ the source location of the current join point
◦ normal, short and long string representations of the current join point
◦ the actual argument(s) to the method or field selected by the current join point
◦ the signature of the method or field selected by the current join point
◦ the target object
◦ the currently executing object
◦ a reference to the static portion of the
AspectState.aj at line 9 Student.java at line 14
Student.java at line 28
Use target , args, and this similarly
Can be done declaratively
◦ Add a parameter to the pointcut declaration
◦ Add && args(s) to the designator
◦ Add parameter to advice designator
◦ Add variable name to advice body
Also all available reflectively
Inter-type Declarations
Add new functionality to an application, new
attributes, new methods, and change inheritance
To do this, you will write normal variable and methods in your aspect, but prefix them with your “classname”
You can then access those fields and methods in
◦ normal java code, or
◦ in your aspects
To get access to the object being references:
◦ Add a parameter to the pointcut name
◦ Add && target(t) to the designator
◦ Add parameter to advice designator
◦ Add variable name to advice body
You can:
◦ add members (id fields, dirty-ness)
◦ add methods (toXML, storeToJDBC)
◦ add types that extend existing types or implement interfaces
◦ declare custom compilation errors or warnings
◦ convert checked exceptions to unchecked
Can use from aspects & regular code
Can do wacky things:
◦ Add concrete fields & methods to interfaces (no constructors)
◦ Modify aspects
◦ Make an existing class dynamically implement an interface
Softening Exceptions Suppress checked as unchecked declare soft : java.io.IOException: execution (* * (..)) && within
(SomeClass); Then does not need to be handled in the code.
Difficult to know if code is advised
Only good tool support in Eclipse
Crossing component boundaries
How will we model?
When usages are appropriate?
Not a Java Specification Request, integration questions
Refactoring can break it!
Logging example
How do you explain the result below?
In Nkalore we have two files: Nkalore.dll and mcs.exe
After compilation we can run the result:
Implement a system component using AOP
Books
◦ Eric Evans, 2003, Domain Driven Design: Tackling Complexity in the Heart of Software
https://www.amazon.com/gp/product/0321125215?ie=UTF8&tag=panesofglass- 20&linkCode=as2&camp=1789&creative=390957&creativeASIN=0321125215
◦ Jimmy Nilsson, 2006, Applying Domain Driven Design and Patterns
https://www.amazon.com/gp/product/0321268202?ie=UTF8&tag=panesofglass- 20&linkCode=as2&camp=1789&creative=390957&creativeASIN=0321268202
◦ Jeffrey Palermo, Ben Scheirman, Jimmy Bogard, 2009, ASP.NET MVC in Action
https://www.amazon.com/gp/product/1933988622?ie=UTF8&tag=panesofglass- 20&linkCode=as2&camp=1789&creative=390957&creativeASIN=1933988622
Blogs
◦ Eric Evans https://dddcommunity.org/
◦ Jimmy Nilsson http://jimmynilsson.com/blog/
◦ Greg Young (Distributed DDD/CQS) http://codebetter.com/blogs/gregyoung/
PPTs
◦ Ryan Riley, Catapult Systems, Inc., Domain Driven Design
Aspect Oriented Programming with AspectJ:
http://www.tomjanofsky.com/AspectJ.pdf
AspectJ tutorial:
http://www.cs.wustl.edu/~mdeters/doc/slides/aspectjtutorial.pdf
AspectJ for Multilevel Security:
http://www.aosd.net/workshops/acp4is/2006/papers/3.pdf
Dynamic analysis of SQL queries:
http://www.info.fundp.ac.be/~staffsem/slides/Cleve.pdf
AOP: http://www.cojan.go.ro/PP/index7.htm, http://www.cojan.go.ro/PP/index8.htm
BPMN: http://www.column2.com/2006/02/investing-in-bpm- webinar/ , http://www.gliffy.com/examples/business-process- diagrams/ , http://www.bpm-book.com/BPMbook/Exercise4-76
AspectJ Tutorial: http://www.tomjanofsky.com/aspectj_tutorial.html
A look at aspect-oriented programming:
http://www.ibm.com/developerworks/rational/library/2782.html
Implementing caching with AspectJ:
http://www.aspectprogrammer.org/blogs/adrian/2004/06/impleme nting_ca.html
Debugging Class Loading with AOP:
http://www.cubeia.com/index.php/articles/63-debug-class-loading
Using AOP in C#:
http://www.codeproject.com/KB/cs/UsingAOPInCSharp.aspx NKalore: http://aspectsharpcomp.sourceforge.net/