Presentation is loading. Please wait.

Presentation is loading. Please wait.

Aspect-Oriented Programming

Similar presentations


Presentation on theme: "Aspect-Oriented Programming"— Presentation transcript:

1 Aspect-Oriented Programming

2 Programming History Procedural programming is the root of it all
Identifies that instructions need to be given in some particular order Identified important constructs variables functions (methods) CS446/546

3 OOP History Introduced in the 1970s with Smalltalk
Took off in the early 1990s incorporated into many languages (e.g., Java, C++) older languages revised to incorporate it (e.g., Ada, BASIC, Fortran) Became the basis for newer languages (e.g., Python, Ruby) Serves as an industry standard CS446/546

4 Object-Oriented Programming
Representation of real-world concepts/ideas as classes/objects Each class has two components: attributes and behaviors Objects are set up to interact with one another CS446/546

5 Separation of Concerns
Guiding principle behind how we organize classes and their attributes/behaviors Design such that each class/attribute/behavior has a very specific problem/need avoid the God object anti-pattern! avoid the spaghetti code anti-pattern! Serves as the motivation for OOP One (unfortunately) popular anti-pattern that emerges in mobile development is Spaghetti Code. In this situation, several different classes become interdependent on each other. This creates problems when new developers pick up existing code, or when new functionality is added to a complex part of the application. Inevitably, when one class is modified, it ends up breaking several other classes. Consider the example of authentication. Some mobile applications only require authentication at specific points in the code. (Example: I can browse content anonymously, but when I want to rate something, I must log in.) A common pitfall would be to pass a reference to the authentication view controller to the content browsing view controller, so that it could be invoked if someone clicks 'rate'. The same (anti) pattern is subsequently applied in several different view controllers. Then, when the authentication code is inevitably changed in the future, all of the existing view controllers "break" and must be repaired. To avoid this situation, the individual view controllers should not directly invoke other view controllers. Instead, they should notify the application that some significant event has occurred. The application's overall workflow controller can then determine how to respond to the event appropriately. This approach provides for loose coupling between the various view controllers. So, for example, if the authentication code changes, only the workflow controller needs to be updated. CS446/546

6 Example - Separation of Concerns
Draw the class diagram for a BankAccount. CS446/546

7 Example Consider a banking application: a very simple method for transferring an amount from one account to another void transfer(Account fromAcc, Account toAcc, int amount) throws Exception { if (fromAcc.getBalance() < amount) { throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); However, this transfer method overlooks certain considerations that would be necessary for a deployed application. It requires security checks to verify that the current user has the authorization to perform this operation. The operation should be in a database transaction in order to prevent accidental data loss. For diagnostics, the operation should be logged to the system log. And so on. A simplified version with all those new concerns would look somewhat like this:

8 Example - Separation of Concerns
Draw the class diagram for a BankAccount. Now add classes/relationships for a database to stores/access information for users/accounts, and a logging class to keep track of transactions to accounts or creation/updating of user information. can be thought of as a telescoping method re: too many parameters CS446/546

9 Cross-cutting Concerns
void transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger) throws Exception { logger.info("transferring money..."); if (! checkUserPermission(user)){ logger.info("User has no permission."); throw new UnauthorizeUserException(); } if (fromAcc.getBalance() < amount) { logger.info("Insufficient Funds, sorry :( "); throw new InsufficientFundsException(); fromAcc.withdraw(amount); toAcc.deposit(amount); //get database connection //save transactions logger.info("Successful transaction. :) "); other interests have become tangled with the basic functionality (sometimes called the business logic concern). Transactions, security, and logging all exemplify cross-cutting concerns.

10 Concerns with Concerns
Not everything can be nicely separated by concerns in OOP Many actors end up interacting with most of the classes databases loggers error detection/correction security We call these cross-cutting concerns CS446/546

11 Cross-Cutting vs Core Concerns
Core concerns are the concerns an application is written for Cross-cutting concerns are those concerns tangentially related to developing an application, but are not the central problems the application is trying to solve CS446/546

12 Exercise - Identifying Concerns
You are creating a new WINGS application for the UW system. This application should enable people to see a list of classes for their campus and register for the upcoming semester. No one except the student’s advisor should have access to the student’s profile. Consider what the core concerns and cross-cutting concerns are here. what are the core concerns? what about cross-cutting concerns? CS446/546

13 Ramifications of Cross-Cutting Concerns in OOP
Violation of separation of concerns Usually manifests in two different ways scattering (code duplication) tangling (significant dependencies) CS446/546

14 Other Ramifications of Cross-Cutting Concerns in OOP
Difficult to understand the main purpose of a method when there is significant overhead Required to make modifications in numerous places when requirements change Difficult to remove the modifications if no longer needed Code reuse is difficult in other applications that do not have similar requirements CS446/546

15 Aspect-Oriented Programming (AOP)
Aims to solve the problems presented by cross-cutting concerns Builds on top of object-oriented programming enriches the vocabulary we have to talk about OOP compliments OOP CS446/546

16 OOP & AOP Design OOP find nouns and verbs, translate them into classes/attributes and methods AOP aids with adjectives and adverbs secure transaction, or logged event CS446/546

17 AOP Implementations C# (via Unity) Lisp Groovy Haskell
Java (via AspectJ) Python Ruby I’ll be using AspectJ CS446/546

18 AOP History Developed in the late 1990s, released in the early 2000s
First released as AspectJ Used in larger projects Java’s Spring Framework Microsoft Transaction Server I’ll be using AspectJ CS446/546

19 AOP - Aspects Encapsulates cross-cutting logic
Used across core concerns Comprised of two parts advice: additional cross-cutting code pointcut: expressions that define where aspects should be used give an example of this: maybe logging? Classes from Bank Aspect that intercepts methods in Bank CS446/546

20 Aspect-oriented Programming
The following are some standard terminology used in Aspect-oriented programming: Cross-cutting concerns: Even though most classes in an OO model will perform a single, specific function, they often share common, secondary requirements with other classes. For example, we may want to add logging to classes within the data-access layer and also to classes in the UI layer whenever a thread enters or exits a method. Even though the primary functionality of each class is very different, the code needed to perform the secondary functionality is often identical. Advice: This is the additional code that you want to apply to your existing model. Example, this is the logging code that we want to apply whenever the thread enters or exits a method. Pointcut: This is the term given to the point of execution in the application at which cross-cutting concern needs to be applied. Example, a pointcut is reached when the thread enters a method, and another pointcut is reached when the thread exits the method. Aspect: The combination of the pointcut and the advice is termed an aspect.

21 Implement Logging in an Aspect
aspect Logger { void Bank.transfer(Account fromAcc, Account toAcc, int amount, User user, Logger logger) { logger.info("transferring money..."); } void Bank.withDraw(User user, int transactionId, Logger logger){ logger.info("User withdraws money"); } // other crosscutting code...

22 Aspect-oriented Programming
Aspect-oriented programming (AOP) is a programming paradigm in which secondary or supporting functions are isolated from the main program's business logic. It aims to increase modularity by allowing the separation of cross-cutting concerns, forming a basis for aspect-oriented software development AOP includes programming techniques and tools that support the modularization of concerns at the level of the source code, while aspect-oriented software development refers to a whole engineering discipline.

23 Aspect-oriented Programming
Consider what happens if we suddenly need to change (for example) the security considerations for the application In the program's current version, security-related operations appear scattered across numerous methods, and such a change would require a major effort Therefore, we find that the cross-cutting concerns do not get properly encapsulated in their own modules. This increases the system complexity and makes evolution considerably more difficult. AOP attempts to solve this problem by allowing the programmer to express cross-cutting concerns in stand-alone modules called aspects. Aspects can contain advice (code joined to specified points in the program) and inter-type declarations (structural members added to other classes). For example, a security module can include advice that performs a security check before accessing a bank account. The pointcut defines the times (join points) that a bank account can be accessed, and the code in the advice body defines how the security check is implemented. That way, both the check and the places can be maintained in one place. Further, a good pointcut can anticipate later program changes, so if another developer creates a new method to access the bank account, the advice will apply to the new method when it executes.

24 Aspect-Oriented Programming (AOP)
Aims to solve the problems presented by cross-cutting concerns Builds on top of object-oriented programming enriches the vocabulary we have to talk about OOP compliments OOP CS446/546

25 AOP - Definition aspect: special type of class that encapsulates cross-cutting code Comprised of two parts advice: the cross-cutting code (e.g., logging) pointcut: expressions that define where advice should be used draw sequence diagram on board CS446/546

26 Pointcut pointcut: named expressions that define where advice should be used Defined by the name and the definition for when to apply advice many options; for now, we’ll be using call(), which defines when some method(s) have been called draw sequence diagram on board CS446/546

27 Advice advice: the cross-cutting code (e.g., logging)
Defined by what point cuts it is interested in, and when to apply advice before: just before the joinpoint after: just after the joinpoint can be specified for whether the method is returning or throwing around: can intercept arguments/return values associated with a joinpoint draw sequence diagram on board CS446/546

28 Pointcuts Serve as the heart of AOP Arguably the most powerful part
let’s us define where we have cross-cutting concerns to advise draw sequence diagram on board CS446/546

29 Aspect-oriented Programming
Aspect-oriented programming entails breaking down a program into distinct parts (so-called concerns, cohesive areas of functionality). All programming paradigms support some level of grouping and encapsulation of concerns into separate, independent entities by providing abstractions (e.g. procedures, modules, classes, methods) that can be used for implementing, abstracting and composing these concerns. But some concerns defy these forms of implementation and are called crosscutting concerns because they "cut across" multiple abstractions in a program. Logging is a common example of a crosscutting concern because a logging strategy necessarily affects every single logged part of the system. Logging thereby crosscuts all logged classes and methods.


Download ppt "Aspect-Oriented Programming"

Similar presentations


Ads by Google