"הפשטה" זה די פשוט ולא כל כך מופשט יוסי גיל סמינר...
TRANSCRIPT
הפשטה"" זה די פשוט ולא כל כך מופשט
יוסי גיל
סמינר קיץ למורים במדעי המחשב
22.6.2004
2/22
Déjà Vu• Stepping into a room, and feeling that you
have already been there…
• This worm and cozy feeling at the back of your head …
• Nice, isn’t it?
In Software …
Déjà Vu = the Bells of Warning
The Fundamental Metaphor of Software
Software is Like Fire, Software is Like Water
Software always changes, and forever will
Software Component
Duplication is Evil
Every change here, should be repeated there…
Software Component
Client 1 Client 2
The Principle of Little Numbers0 > 1: What you don't know cannot hurt you. Information hiding, encapsulation, table driven programming, modularity, etc.
1 > 2: If the same thing occurs twice in the code, then it occurs one time too many.
Software is constantly subject to change. As changes occur, maintaining the two almost identical parts will become a nightmare.
for (ever) {write code;while (exist(similar parts)) {
extract identical portion;rewrite code;
}}
Abstraction• Abstraction: find commonality of several
phenomena
Good abstraction:– Ignore the “irrelevant” details– Find the “relevant” commonalities– Maximize “relevant” commonalities
• Abstractions are almost invariably relative to a domain of interest
Phenomenon A Phenomenon B
Phenomenon C
SomeAbstraction
Phenomenon 1 Phenomenon 2
Phenomenon 3
AnotherAbstraction
Abstraction and ReusabilityBenefits:
– Reduce development cost: one component instead of many
– Promote reliability: • exercise component from many different aspects• no need to remember to correct the same error twice
Software Component
Client 1 Client 2
Abstraction is Relative to Domain
Abstraction focuses upon the essential characteristics of some object, relative to the perspective of the viewer.
Abstract at the Right Level
An IQ Test
• Table and Chair?• Cat and Dog?• Dog and Wolf?• Pencil and Cup?• School and Bank?• Decline and wriggle?• Jewels and Apartment?• Salary raise and court-of-law?• Army and clothing?• Aesophagus and genealogy?
What’s in common to:
Taxonomy
Abstraction ofAbstractions
Phenomenon 1 Phenomenon 2
Phenomenon 3
An Abstraction
Phenomenon A Phenomenon B
Phenomenon C
AnotherAbstraction
TAXONOMY
Taxonomy: Abstraction of Abstractions tax·on·o·my 1. The classification of organisms in an ordered system that indicates natural relationships. 2. The science, laws, or principles of classification; systematics. 3. Division into ordered groups or categories: “Scholars have been laboring to develop a taxonomy of young killers”
Successful Taxonomies:• Taxonomy: the ultimate goal of the abstraction
process• Examples:
– Linguistic: classification of languages.– Biology: kingdom, phylum, subphylum, class, order,
family, genus, species.– Chemistry: the periodic table of the elements.– Mathematics: Algebraic structure - group, ring,
commutative-ring, skewed-field, field, algebra, ...– Computer Science: Kinds of polymorphism.
Descartes: “the discovery of an order is no easy task ... yet once the order has been discovered there is no difficulty at all in knowing it.”
Meta-Abstraction• Abstraction of the abstraction process:
– Recipes for finding the “right” abstractions.
Phenomenon A Phenomenon B
Phenomenon C
Yet Another UsefulAbstraction
Phenomenon 1 Phenomenon 2
Phenomenon 3
Some UsefulAbstraction
MetaAbstraction
15/22
Abstractions in Software
• The programming language provides mechanisms for representing our mental abstractions.
• Each mechanisms relies on a metaphor
16/22
Familiar Mechanisms and Metaphors
• Procedure – the statement metaphor– Writeln(“hello”); => procedure print()
• Function – the expression metaphor– odd(b) => isOpen(f)
• Type – the primitive type metaphor– X: integer => TYPE A=array[1..100] of real;
VAR x: A;
• Record – the folder metaphor
Programming Paradigms
• Paradigm == Kinds of Abstractions Employed• Main Paradigms:
– Procedure-oriented: Algorithms– Object-oriented: Classes and objects– Logic-oriented: Goals (predicate
calculus)– Rule-oriented: If-then rules– Constraint-oriented: Invariant relationships
Reactions to New Technology
Eureka!!! OOP is the solution
It will never work!
It’s trivial!
This is what we have been doing all the time!
There is still much to do...
Evolution leading to OOP: #1/5
Decide on a data/data base model;write simple utilities around it:
Brute-force attack: Fortran/Cobol/Data bases
Global Data
Proc 1 Proc 4Proc 2 Proc 3
Evolution leading to OOP: #2/5Decide which procedures you want;use the best algorithms you can find:
Procedural: Pascal
Proc 3
Type 1
Proc 1
Proc 2
Type 2 Var 1 Var 2
Algorithms + Data Structures = Programs N. Wirth
Evolution leading to OOP: #3/5
Decide which modules you want;partition the program so that data is hidden in modules:
Data Hiding: Modula-2/Turbo-Pascal
Module 2
Type 1
Var 1
Module 3
Var 2
Type 2
Module 1
Proc 1
TypeVar
Proc 2Usage
Evolution leading to OOP: #4/5
Type 2Type 1
Op 1
Var 1Var 2
Op 2
Data Abstraction: ADA
Decide which types you want;provide a full set of operations for each type:
Op 1Op 2
Op 3
Var 1Var 2Var 3
In contrast with modules, types can be “instantiated”
Evolution leading to OOP: #5/5OOP:
Decide which classes you want;provide a full set of operations for each class;make commonality explicit by using inheritance and genericity:
The Power of Inheritance: Reduction in size of the Booch Components, originally written in Ada as a result of the port to C++.
Syllogisms
X is good.Object oriented is good.
X is object oriented.
X = Ada, corelDraw, Roger King’s Cat, Visual Basic, Microsoft Excel, Windows-NT,
Communication programs, ...
25/22
Conclusions
• déjà vu is a danger signal!• Abstraction is not abstract.• Abstraction cannot be taught.• Teach and study Abstraction
mechanisms• Meta abstraction is vague and/or
trivial• Strive to build a taxonomy
26/22
method transferAmount(acct A, acct B, amount) {valid = verifyUserCredentials(TRANSFER_FUNDS);if (!valid) reportSecurityError(); exit;DB.startTransaction();currentA = A.getBalance();currentB = B.getBalance();if (currentA – amount < 0) DB.rollback(); reportOverdraft(); exit;A.setBalance(currentA – amount);B.setBalance(currentB + amount);DB.commit();if (DB.error()) reportDbError(); exit;log.log(“Transferred amount from A to B”);
}
SECURITY
TRANSACTION MANAGEMENT
BUSINESS LOGIC
LOGGING
Programrequirements
AspectualDecomposition
(conceptual process)
Clearly distinctconcerns
AspectWeaving
(mechanical process)
Executable
Untangling the Web We WeaveUntangling the Web We Weave
27/22
Aspect-Oriented Programmingto the Rescue
• Design the core “business logic”• Define aspects which are “transformation operators”.
– Example: a logging operator
• Aspect Operator Program Module– Operators can be reused for many tasks– Should not break the operand– Transformation is packaged
• Apply “aspect modules” to adapt the code to support:– Logging– Security– Persistence …
28/22
The Enemy of the Good…• Two conflicting forces in software design:
– If it is good, you want to add aspectsto it …
– When you add aspects, youchange it…
– In changing it, you might damage it…– …now it is not so good anymore!
Le mieux est l’ennemidu bien.
29/22
Code Transformation• An aspect is a “code transformer”.
– However, there is no simple, unified metaphor or semantics for definition or application of aspects.
• Ideally, we would like the transformer to be:– Expressive– Modular– Structure-preserving, i.e., tightly coupled with the
underlying language.– Simple
• Bad example:– C pre-processor (which does not know anything about
C….)• Good example:
– mixins -- an abstract sub-class mechanism.
30/22
What is “Aspect Application”?• How can we make AOP more than a
fancy pre-processor?
• Uncontrolled and non-systematic change leads to anarchy.– Multiple applications of the same transformer?– Specification of application order?– Parameters to the transformer?– Time of transformation? (Compile/Link/Run)– Does the non-transformed version remain? Are
the two versions compatible?
31/22
Our Solution• Reduce all above questions to the familiar
domain of OOP– Motivation & Inspiration: Enterprise Applications
and J2EE deployment process.
• In a nutshell, aspect application is a form of subclassing (slightly restricted, slightly generalized…)– Strong evidence that “this works”– A natural extension of an existing “deployment”
process (more later)
Capture the mode of operation of banks, government agencies, insurance companies, hospitals…–Make the world go round
Java 2, Enterprise Edition - a modern and popular middleware framework for enterprise applications, implemented by e.g., IBM WebSphere App Server
32/22
Aspects as “Reimplements” Operators
Given a class C, aspect A, the application C’=A[[C,p1,…,pn]] is a new class such that
1. C’ has the same type as C. (cannot declare variables of type C’)2. May have additional fields.3. May have a modified behavior.
Simple subclassing:
1. Creates a subtype by adding more functions to the protocol.
2. Extends the structure definition by adding more fields.
3. Modifies the behavior by replacement and refinement
A class in OOP is:
1. A type declarationC p;
2. Template for object creation (constructor, field layout etc.)
p = new C();3. An implementation
p.m();
Actual parameters p1…pn make C fit into
the slots that A expects
33/22
Example: Simple Logging Aspect
aspect Logging { before every method of the operand { print(“Method started: ” + currentMethodName); }
after every method of the operand { print(“Method completed”); }}
Interface
Base Implementation
Augmented Implementation
Aspect Module
optional parameters
34/22
Applying an Aspect to a Class Hierarchy
C1
C2
C4
C3
C1’
C2’ C3’
C4’No inheritance relationship
between the re-implementationsSince no new types are defined, this does not disturb polymorphism!
35/22
Parameterized Example: A Transaction Aspect
aspect Transactions<T, // methods of the operand that require a transaction (possible existing) S // methods of the operand that require their own tx (possibly nested)
> {before every method in S { startNewTransaction(); }before every method in T
{ if (!inTx) startNewTransaction(); }
after every method in TS { if (newTxStarted) commit(); }
}
• Every application of this aspect must provide values for parameters T and S
36/22
AspectJ2EE as a Distilled Code Transformer
ClassInheritanceMixins
AspectJ2EE
Aspects
Structure templateDefineExtend
Template for structure extension
Template for structure extension
New TypeDeclareSubtype specific parent
Template for subtyping limited
set of parents (opreands)
No
Code imple-mentationYes
Modify specific parent
Modify limited set of parents
(operands)
Modify any operand
ParametersOnly with Templates
NoOnly for parent
class
Expressive binding
mechanism
37/22
Enterprise JavaBeans (EJBs)
• Represent the data model in J2EE applications• Developers provide the business logic
– “Transfer amount X from account A to account B”
• J2EE provides everything else
– Services: Security, transactions, persistence…
UPDATE account SET balance = balance + 100 WHERE id = 12345
SELECT balance FROM account WHERE id = 12345
Account a = AccountFactory.find(12345);a.deposit(100);float b = acct.getBalance();
38/22
J2EE is not as good as AOP
• Closed and pre-defined set of services– Need a different service? Tough Luck! e.g., to add logging
support, you’ll have to use scattered and tangled code.
• Fixed implementation of services– e.g., J2EE security is role-based. Need name-based
security? Tough Luck!
• EJBs are hard to program– Just look at the standard specification– You mustn’t do this, you mustn’t do that…
• e.g., “this” may not be passed as a method argument
39/22
The Deployment Process
• J2EE services are added to business logic during the deployment process
• Done without modifying code – only generating support code– Subclasses– Factory classes– RMI stubs/skeletons
Define EJB Services as Aspects.
Aspect application becomes part of the
deployment process .
40/22
J2EE Deployment
«interface»javax.ejb.EntityBean
+withdraw()+deposit()+getBalance() : float
«interface»Account
«interface»javax.ejb.EJBObject
«interface»javax.ejb.EJBHome
+create() : Account+findByPrimaryKey() : Account
«interface»AccountHome
+withdraw()+deposit()+getId() : String+setId()+getBalance() : float+setBalance()+ejbLoad()+ejbStore()+ejbCreate()+ejbActivate()+ejbPassivate()+ejbRemove()+setEntityContext()+unsetEntityContext()
AccountBean
User-provided classes
«interface»javax.ejb.EntityBean
+withdraw()+deposit()+getBalance() : float
«interface»Account
«interface»javax.ejb.EJBObject
«interface»javax.ejb.EJBHome
+create() : Account+findByPrimaryKey() : Account
«interface»AccountHome
+withdraw()+deposit()+getBalance() : float
_Account_Stub
+getId() : String+setId()+getBalance() : float+setBalance()
-id : String-balance : float
ConcreteAccount_b7e62f65
+create() : ConcreteAccount_b7e62f65+findByPrimaryKey() : ConcreteAccount_b7e62f65
EJSRemoteCMPAccountHome_b7e62f65
«creates»
+withdraw()+deposit()+getId() : String+setId()+getBalance() : float+setBalance()+ejbLoad()+ejbStore()+ejbCreate()+ejbActivate()+ejbPassivate()+ejbRemove()+setEntityContext()+unsetEntityContext()
AccountBean
Many, many more
classes generated
…
41/22
AspectJ2EE Deployment
«interface»javax.ejb.EntityBean
+withdraw()+deposit()+getBalance() : float
«interface»Account
«interface»javax.ejb.EJBObject
«interface»javax.ejb.EJBHome
+create() : Account+findByPrimaryKey() : Account
«interface»AccountHome
+withdraw()+deposit()+getId() : String+setId()+getBalance() : float+setBalance()+ejbLoad()+ejbStore()+ejbCreate()+ejbActivate()+ejbPassivate()+ejbRemove()+setEntityContext()+unsetEntityContext()
AccountBean
Application of Four Aspects to an EJB
«interface»javax.ejb.EntityBean
+withdraw()+deposit()+getBalance() : float
«interface»Account
«interface»javax.ejb.EJBObject
«interface»javax.ejb.EJBHome
+create() : Account+findByPrimaryKey() : Account
«interface»AccountHome
+withdraw()+deposit()+getBalance() : float
_Account_Stub
+AdvAccount_Persistence()+_init()+setId()+setBalance()+ejbLoad()+ejbStore()+ejbCreate()+ejbActivate()+ejbPassivate()+ejbRemove()
-conn : Connection-dirty : boolean
AdvAccount_Persistence
+create() : AdvAccount_Transactions+findByPrimaryKey() : AdvAccount_Transactions
ConcreteRemoteAccountHome
+AdvAccount_Security()+_init()+withdraw()+deposit()
-principle : String
AdvAccount_Security
+AdvAccount_Transactions()+_init()+withdraw()+deposit()+getId() : String+setId()+getBalance() : float+setBalance()
-context : TransactionContext-modes : Hashtable
AdvAccount_Transactions
«creates»
+AdvAccount_Lifecycle()+getId() : String+setId()+getBalance() : float+setBalance()+ejbLoad()+ejbStore()+ejbCreate()+ejbActivate()+ejbPassivate()+ejbRemove()+setEntityContext()+unsetEntityContext()+getEntityContext()
-id : String-balance : float-ctx : EntityContext
AdvAccount_Lifecycle
+withdraw()+deposit()+getId() : String+setId()+getBalance() : float+setBalance()
AccountBean
The generatedclasses aresubclasses
42/22
Join Points Supported by Deployment/Subclassing
Data access
[before | after] [property | private field] [get | set]
Code
[before | after | around] [method | c’tor1 | remote]
[after throwing | after returning] [method | c’tor ]
Control flow
[cflow | cflowbelow]
[catch]
1 Standard Java restrictions on constructors apply
43/22
The Deployment Descriptor
• XML syntax is used to specify the aspect application details– Order of application, parameters, etc.– Conceptually based on J2EE’s XML Deployment Descriptors
• For example:
<entity id=“Account”><ejb-name>Account</ejb-name><ejb-class>aspectj2ee.demo.AccountBean</ejb-class><aspect>
<aspect-class>aspectj2ee.core.Lifecycle</aspect-class></aspect><aspect>
<aspect-class>aspectj2ee.core.Security</aspect-class><pointcut name=“secured”>execution(*(..))</pointcut><value name=“requiredRole”>User</value>
</aspect></entity>
44/22
Remote Calls
• The deployment process also generates RMI stubs and skeletons
• If we allow the user to control the process, he can also control this facet
• In particular, we can define aspects for handling tier-cutting concerns
• A single module each (without scattered code) for handling:– Encryption/decryption of client-server communications– Data compression– Memoization– Client-side precondition checking
• Similar to “Remote Pointcut”, Nishizawa, Chiba and Tatsubori (AOSD ’04)
45/22
Summary
1. A smooth embedding of AOP in OOP
2. Proof of the pudding: works in real-world enterprise applications
3. Harmonious marriage of J2EE and AOP
4. New weaving mechanism using the deployment process
5. Realizing tier-cutting concerns with aspects
46/22
And they lived happily ever after?
Integration with WebSphere? Wedding AOP with other J2EE sub-
technologies? Servlets JSP (Java Server Pages) Web services
User study? Refactoring existing projects into this
model?