460 likes | 585 Views
"הפשטה" זה די פשוט ולא כל כך מופשט. יוסי גיל סמינר קיץ למורים במדעי המחשב 22.6.2004. 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.
E N D
"הפשטה" זה די פשוט ולא כל כך מופשט יוסי גיל סמינר קיץ למורים במדעי המחשב 22.6.2004
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
Duplication is Evil Every change here, should be repeated there… Software Component Software Component Client 2 Client 1
The Principle of Little Numbers 0 > 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 phenomenaGood abstraction: • Ignore the “irrelevant” details • Find the “relevant” commonalities • Maximize “relevant” commonalities • Abstractions are almost invariably relative to a domain of interest
Abstraction and Reusability Benefits: • 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.
An IQ Test What’s in common to: • 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?
Taxonomy 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” Taxonomy: Abstraction of Abstractions
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.
Abstractions in Software • The programming language provides mechanisms for representing our mental abstractions. • Each mechanisms relies on a metaphor
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
This is what we have been doing all the time! There is still much to do... It will never work! It’s trivial! Reactions to New Technology Eureka!!! OOP is the solution
Proc 2 Proc 3 Proc 1 Proc 4 Evolution leading to OOP: #1/5 Brute-force attack: Fortran/Cobol/Data bases Decide on a data/data base model; write simple utilities around it: Global Data
Proc 1 Type 2 Var 1 Proc 2 Evolution leading to OOP: #2/5 Procedural: Pascal Decide which procedures you want; use the best algorithms you can find: Type 1 Proc 3 Var 2 Algorithms + Data Structures = Programs N. Wirth
Evolution leading to OOP: #3/5 Data Hiding: Modula-2/Turbo-Pascal Decide which modules you want; partition the program so that data is hidden in modules: Module 2 Module 1 Type 1 Var Module 3 Type Usage Proc 2 Proc 1 Var 2 Var 1 Type 2
Evolution leading to OOP: #4/5 In contrast with modules, types can be “instantiated” Data Abstraction: ADA Decide which types you want; provide a full set of operations for each type: Type 1 Type 2 Op 1 Op 2 Op 1 Op 2 Var 1 Var 2 Var 3 Var 1 Var 2 Op 3
Evolution leading to OOP: #5/5 OOP: Decide which classes you want; provide a full set of operations for each class; make commonality explicit by using inheritanceand 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, ...
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
Untangling the Web We Weave Untangling the Web We Weave SECURITY 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”); } BUSINESS LOGIC TRANSACTION MANAGEMENT LOGGING Executable Clearly distinct concerns Program requirements Aspectual Decomposition (conceptual process) Aspect Weaving (mechanical process)
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 …
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.
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.
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?
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
Aspects as “Reimplements” Operators A class in OOP is: • A type declaration C p; • Template for object creation (constructor, field layout etc.) p = new C(); • An implementation p.m(); Simple subclassing: • Creates a subtype by adding more functions to the protocol. • Extends the structure definition by adding more fields. • Modifies the behavior by replacement and refinement Given a class C, aspect A, the application C’=A[[C,p1,…,pn]] is a new class such that • C’ has the same type as C. (cannot declare variables of type C’) • May have additional fields. • May have a modified behavior. Actual parameters p1…pn make C fit into the slots that A expects
Example: Simple Logging Aspect Interface optional parameters Base Implementation Aspect Module Augmented Implementation • aspect Logging { • beforeevery method of the operand { • print(“Method started: ” + currentMethodName); • } • afterevery method of the operand{ • print(“Method completed”); • } • }
Applying an Aspect to a Class Hierarchy C1 C1’ C2 C2’ C3 C3’ No inheritance relationship between the re-implementations Since no new types are defined, this does not disturb polymorphism! C4 C4’
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(); } beforeevery method in T { if (!inTx) startNewTransaction(); } afterevery method in TS { if (newTxStarted) commit(); } } • Every application of this aspect must provide values for parameters T and S
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();
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
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.
J2EE Deployment Many, many more classes generated… User-provided classes
AspectJ2EE Deployment Application of Four Aspects to an EJB The generated classes are subclasses
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
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>
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)
Summary • A smooth embedding of AOP in OOP • Proof of the pudding: works in real-world enterprise applications • Harmonious marriage of J2EE and AOP • New weaving mechanism using the deployment process • Realizing tier-cutting concerns with aspects
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?