SlideShare a Scribd company logo
Yan Cui
Server-side Developer @
“Our mission is to build fun games and game apps that
people can play, anywhere, anytime.”
 Overview
 Cross-Cutting Concerns
 AOP
 What’s in it for you
 AOP
 Terminologies
 AOP and OOP
 Solutions
 Q&A
The PROBLEM…
Image by Mark RohdeImage by Mike Rohde
Cross-Cutting Concerns
Function
Requirements
Non-Functional
Requirements
Production
Code
=+
 Cuts across multiple abstractions
 Difficult to decompose
 High-coupling
 Boilerplate code
 Code tangling and scattering
 Poor traceability
 Lower productivity
 Less code reuse
 Harder refactoring
The SOLUTION…
“AOP is a programming paradigm which aims to
increase modularity by allowing the separation
of cross-cutting concerns”
- wikipedia
Coding is HARD
AOP makes
it EASY
Introduction to Aspect Oriented Programming
Image by Mark Rohde
AOP
Introduction to Aspect Oriented Programming
 Centralize concerns implementation
 Intercept method calls
 Inject new behaviour
 More reusable code
 Cleaner code
What’s in it for YOU?
 Write less code
 Read less code
 More concise and easy to understand
 More maintainable
 Fewer code =
 Less boilerplate code
 More interesting work
 Increased attention
 More PRODUCTIVITY!
FEWER DEFECTS!
Diving a little deeper…
 Join Point
 Place where behaviour can be added
 Advice
 Code that can be injected at join points
 Point cut
 Join points where advice should be applied
 Aspect
 Container holding point cuts and advice
 Weaving
 Combines advices with point cuts
 AOP is complementary to OOP
 AOP targets a specific problem
 Code modularization
 OOP – Real world objects
 AOP – Functionalities
 Help you S.O.L.I.Dify your code
 Single responsibility
 Open/close
 You can do AOP via:
 Dynamic Proxies
 Functional Programming
 Code Generation
 Dynamic Languages
 Static Weaving
AOP via...
 IoC framesworks (Castle, Spring.Net)
 Dynamic interceptors
Image by Mark Rohde
Dynamic Proxies
Introduction to Aspect Oriented Programming
 Advantages
 Can use existing DI framework
 Some frameworks provides built-in aspects
 Aspects can be configured after build
 Disadvantages
 Significant change to base code required to adapt
 Limited AOP features
 Do not work on static, non-public methods
 Do not work on fields, properties, or events
 Higher run-time overhead
 No build-time verification
 Objects must be instantiated using the container
Class, is AOP the same as
Dependency Injection?
NOOOO Sir!!
AOP via...
Image by Mark Rohde
Functional
Programming
Introduction to Aspect Oriented Programming
 Advantages
 No external dependencies
 Disadvantages
 Requires modification to every function
 No support for matching rules
 Manual aspect composition
AOP via…
 T4, CodeSmith Tools
 Advantages
 Easy to generate complex source code
 Disadvantages
 Input is usually XML
 Cannot inject new behaviour to existing code
AOP via…
Image by Mark Rohde
Dynamic Languages
 Advantages
 Meta-programming is easy
 Disadvantages
 Switching to a dynamic language can be scary
 No (limited) Visual Studio tooling
AOP via…
 PostSharp, AspectJ
 Uses low-level MSIL transformation
 Compile time
Aspect Decomposition
Aspects Core program
Aspect Recomposition
Requirements
Final System
 Aspectual Decomposition
 Identify primary and cross-cutting concerns
 Concern Implementation
 Implement concerns separately
 Primary concern as Core Component using OO
 Cross-cutting concerns as aspect
 Aspectual Recomposition
 Aspect weaver to weave the separately
implemented code into a final system
Image by Mark Rohde
PostSharp
 Advantages
 Most complete support of AOP features
 Aspect usage is verified at build time
 Better runtime performance
 Disadvantages
 Increased build time
 New to many developers
PostSharp Training
@ SkillsMatter, London
January 19-20, 2012
http://www.sharpcrafters.com/training
jobs@iwi.com
Thank You!
Yan Cui
@theburningmonk
Introduction to Aspect Oriented Programming

More Related Content

PPTX
Aspect Oriented Programing - Introduction
PPTX
Introduction to Aspect Oriented Programming (DDD South West 4.0)
PPTX
Introduction To Aspect Oriented Programming
PPTX
Introduction to Aspect Oriented Programming
PPT
Aspect Oriented Programming
PPT
Aspect oriented architecture
PPTX
Intro To AOP
PPTX
Introduction To AOP
Aspect Oriented Programing - Introduction
Introduction to Aspect Oriented Programming (DDD South West 4.0)
Introduction To Aspect Oriented Programming
Introduction to Aspect Oriented Programming
Aspect Oriented Programming
Aspect oriented architecture
Intro To AOP
Introduction To AOP

What's hot (19)

PPTX
Cqrs and Event Sourcing Intro For Developers
ODP
Beyond Unit Testing
PDF
Solid principles
ODP
Documenting code yapceu2016
ODP
Documenting Code - Patterns and Anti-patterns - NLPW 2016
PPTX
Code Review tool for personal effectiveness and waste analysis
KEY
Client Side Unit Testing
PPT
Integrating the compiler with unit testing
PPTX
Unit tests benefits
PPT
Code Review
PDF
Code Review Tool Evaluation
PDF
Software testing
PDF
10 Benefits of Automated Testing
PPT
Microservices
PDF
Scrum Events and Artifacts in Action
PDF
How to Effectively Test Your Chatbot | Rasa Summit
PPTX
Code Review
PDF
DevOps & Technical Agility: From Theory to Practice
DOCX
Code review guidelines
Cqrs and Event Sourcing Intro For Developers
Beyond Unit Testing
Solid principles
Documenting code yapceu2016
Documenting Code - Patterns and Anti-patterns - NLPW 2016
Code Review tool for personal effectiveness and waste analysis
Client Side Unit Testing
Integrating the compiler with unit testing
Unit tests benefits
Code Review
Code Review Tool Evaluation
Software testing
10 Benefits of Automated Testing
Microservices
Scrum Events and Artifacts in Action
How to Effectively Test Your Chatbot | Rasa Summit
Code Review
DevOps & Technical Agility: From Theory to Practice
Code review guidelines

Similar to Introduction to Aspect Oriented Programming (20)

PPTX
Aspect oriented programming
PPTX
Introduction to Aspect Oriented Programming by Donald Belcham
PPTX
仕様決定、部品化、ディレクションがなぜ重要か
PDF
What Web Framework To Use?
PDF
Lennart Regebro What Zope Did Wrong (And What To Do Instead)
PDF
Lennart Regebro What Zope Did Wrong (And What To Do Instead)
PPTX
PDF
Beyond the Oracle Forms Horizon: from Forms to ADF in minutes
PDF
Oracle Forms Conversion "An automated Approach"
PPTX
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...
PDF
Javascript Framework Roundup FYB
PDF
TDD - Cultivating a Beginner's Mind
PPT
Aspect oriented programming in .Net
PDF
Apex triggers i
PDF
NetWork - 15.10.2011 - Applied code generation in .NET
PPTX
Introduction to Java Part-2
PDF
API Centric Development in PHP
PDF
Metaprogramming Go
PDF
API Design Workflows
PPSX
Introduction to Java
Aspect oriented programming
Introduction to Aspect Oriented Programming by Donald Belcham
仕様決定、部品化、ディレクションがなぜ重要か
What Web Framework To Use?
Lennart Regebro What Zope Did Wrong (And What To Do Instead)
Lennart Regebro What Zope Did Wrong (And What To Do Instead)
Beyond the Oracle Forms Horizon: from Forms to ADF in minutes
Oracle Forms Conversion "An automated Approach"
Debugging,Troubleshooting & Monitoring Distributed Web & Cloud Applications a...
Javascript Framework Roundup FYB
TDD - Cultivating a Beginner's Mind
Aspect oriented programming in .Net
Apex triggers i
NetWork - 15.10.2011 - Applied code generation in .NET
Introduction to Java Part-2
API Centric Development in PHP
Metaprogramming Go
API Design Workflows
Introduction to Java

More from Yan Cui (20)

PDF
How to win the game of trade-offs
PDF
How to choose the right messaging service
PDF
How to choose the right messaging service for your workload
PDF
Patterns and practices for building resilient serverless applications.pdf
PDF
Lambda and DynamoDB best practices
PDF
Lessons from running AppSync in prod
PDF
Serverless observability - a hero's perspective
PDF
How to ship customer value faster with step functions
PDF
How serverless changes the cost paradigm
PDF
Why your next serverless project should use AWS AppSync
PDF
Build social network in 4 weeks
PDF
Patterns and practices for building resilient serverless applications
PDF
How to bring chaos engineering to serverless
PDF
Migrating existing monolith to serverless in 8 steps
PDF
Building a social network in under 4 weeks with Serverless and GraphQL
PDF
FinDev as a business advantage in the post covid19 economy
PDF
How to improve lambda cold starts
PDF
What can you do with lambda in 2020
PDF
A chaos experiment a day, keeping the outage away
PDF
How to debug slow lambda response times
How to win the game of trade-offs
How to choose the right messaging service
How to choose the right messaging service for your workload
Patterns and practices for building resilient serverless applications.pdf
Lambda and DynamoDB best practices
Lessons from running AppSync in prod
Serverless observability - a hero's perspective
How to ship customer value faster with step functions
How serverless changes the cost paradigm
Why your next serverless project should use AWS AppSync
Build social network in 4 weeks
Patterns and practices for building resilient serverless applications
How to bring chaos engineering to serverless
Migrating existing monolith to serverless in 8 steps
Building a social network in under 4 weeks with Serverless and GraphQL
FinDev as a business advantage in the post covid19 economy
How to improve lambda cold starts
What can you do with lambda in 2020
A chaos experiment a day, keeping the outage away
How to debug slow lambda response times

Recently uploaded (20)

PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Building Integrated photovoltaic BIPV_UPV.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
KodekX | Application Modernization Development
PDF
Per capita expenditure prediction using model stacking based on satellite ima...
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PPTX
Spectroscopy.pptx food analysis technology
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Dropbox Q2 2025 Financial Results & Investor Presentation
Building Integrated photovoltaic BIPV_UPV.pdf
Electronic commerce courselecture one. Pdf
MIND Revenue Release Quarter 2 2025 Press Release
Programs and apps: productivity, graphics, security and other tools
Advanced methodologies resolving dimensionality complications for autism neur...
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
KodekX | Application Modernization Development
Per capita expenditure prediction using model stacking based on satellite ima...
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Spectroscopy.pptx food analysis technology
The Rise and Fall of 3GPP – Time for a Sabbatical?
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Spectral efficient network and resource selection model in 5G networks
Encapsulation_ Review paper, used for researhc scholars
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx

Introduction to Aspect Oriented Programming

Editor's Notes

  • #6: Definition: A Cross-Cutting Concern is a concern your application needs to address that is unrelated to your application’s problem domain, and ‘cuts across’ other concerns. Examples: Typically non-functional requirements such as tracing, logging, persistence, transaction control, security, error handling Cross-cutting concerns are usually difficult to decompose from the rest of the system and results in: tangled code, concerns are interwoven with each other in a module scattered code, concerns are dispersed over many modules high coupling Addressing cross-cutting concerns usually means adding boilerplate code to your application, increasing both the size and complexity of your code, and the blast radius of any change that are not related to the problem domain, e.g. changing the persistence media.
  • #8: Definition: A Cross-Cutting Concern is a concern your application needs to address that is unrelated to your application’s problem domain, and ‘cuts across’ other concerns. Examples: Typically non-functional requirements such as tracing, logging, persistence, transaction control, security, error handling Cross-cutting concerns are usually difficult to decompose from the rest of the system and results in: tangled code, concerns are interwoven with each other in a module scattered code, concerns are dispersed over many modules high coupling Addressing cross-cutting concerns usually means adding boilerplate code to your application, increasing both the size and complexity of your code, and the blast radius of any change that are not related to the problem domain, e.g. changing the persistence media.
  • #9: Poor traceability – multiple concerns in the same module breaks linkage between requirement and its implementation, making it harder to understand what a piece of code is doing to address the problem domain. Lower productivity – developers are spending too much time and attention to peripheral issues rather than the problem domain. Less code reuse – boilerplate code propagated through cut and paste… no code reuse here! Harder refactoring – changing requirements means touching many modules for a single concern.
  • #10: Which finally brings us to aspect oriented programming, and I’ll give you a second to read this quick definition from Wikipedia.
  • #13: Take the ‘GetBookById’ method we ended up with earlier, now let’s give ourselves a magic hat and let the hat devour that ugly piece of code, and with a touch of AOP magic we’ll get back a cleaner, more elegant and readable version of the ‘GetBookById’ method. Under the hood, the two versions are the same, both log when they enter and exit the method, and both log any exceptions, also both versions of the code perform validation against the ‘id’ parameter to make sure that it’s not a default Guid.
  • #15: Whist this is useful, it will still cause a lot of clutter when you have to apply the same set of attributes to many methods. But worry not, another feature of AOP is the ability to multicast the same aspects into many places in your code, this feature is called Point Cut.
  • #16: To summarize, AOP allows you to centralize your implementation of cross-cutting concerns. It gives you a nice framework to intercept method calls and inject new behaviour with little change to your code. Once you’ve modularized your code that deal with the cross-cutting concerns, you are able to reuse them in other projects. This lets you write more reusable code and cleaner code.
  • #17: That’s all very nice, but why should you care about writing reusable and clean code? What do you get out of it?
  • #18: Well, for one, you end up writing less code, and therefore you will need to read less code too. The code that you end up reading will be more concise and easy to understand as they’re no longer convoluted by cross-cutting concerns. As you reduce the complexity of your code, it becomes more maintainable too.
  • #19: Writing fewer lines of code means less chance for us to get it wrong, and therefore fewer defects in our code. You have to less boilerplate code, and that makes your work more interesting, and therefore you pay more attention to what you do. So all and all, you get a healthy boost of productivity when you take advantage of what AOP has to offer!
  • #20: Now that you have a rough idea of what AOP is and how it can help you, let me help you get a sense of how you go about using it in practice. Before we do, let me give you a 2-minute crush course on the terminologies used in AOP.
  • #21: Join points are places in your code where an aspect can be inserted, for example, before and after a method call, when a method excepts, or when field or property is being accessed. An advice is a piece of code that can be injected at join points to add new behaviour. This is the boilerplate that you had taken out from your code so that you can encapsulate it into an aspect and then inject it in whilst keeping your code pretty. A point cut is a set of join points where an advice can be applied. It can be attribute drive, like the earlier example of ‘GetBookById’ method where we applied the two attributes to the method. Or it can be filter driven, like the second example where we applied the attributes to the class instead and targeted methods that met our criteria. When a point cut is matched, advice can be executed. An aspect contains point cuts and advice, it is to AOP what class is to OOP, whereas classes holds methods and properties, aspects holds point cuts and advice. Weaving is the process of taking the advice and injecting them into the point cuts in the core component and compose the final result.
  • #22: AOP and OOP are not mutually exclusive; AOP is in fact complimentary to OOP and help you become a better OOP developer by helping you enforce some important design principles of OOP. Unlike OOP, functional programming or declarative programming, which are general purpose paradigms aimed to solve most of the programming problems we face, and all competing to be the core paradigm of a language. AOP on the other hand, is a paradigm which attempts to solve one very specific problem. AOP and OOP both encourage code modularization and encapsulation, which leads to better code reusability and maintainability. The difference between the two paradigms come in the form of WHAT they modularize on: - OOP modularizes on basis of real world entities AOP modularizes on basis of functionalities
  • #23: For those of you who aren’t familiar with the SOLID principles, they stand for: Single responsibility principle: an object should have only one responsibility Open/Close principle: objects should be open for extension, but closed for modification Liskov substitution principle: objects should be replaceable with instances of their subtypes without altering the correctness of that program Interface segregation principle: many specific interfaces are better than one general purpose interface Dependency inversion principle: one should depend upon abstraction rather than implementations These are 5 principles that can help you create more maintainable software with fewer defects. Most of you should be familiar with the dependency inversion principle already because that’s the problem that IoC frameworks solve and IoC frameworks are extremely popular nowadays. You can use AOP to help you better adhere to these principles, for instance, by using AOP to remove the cross-cutting concerns from your core program it becomes easier for you to follow the single responsibility principle. Similarly, using point cut and multicast attribute as I demonstrated earlier, you are able to inject new behaviour into existing classes without modifying them, hence not breaking the open/close principle.
  • #24: So hopefully that’s sufficient evidence for you to want to give AOP a go, but in terms of actually start doing some aspect-oriented programming you have quite a number of different options, including: Dynamic proxies with IoC frameworks - Functional programming using higher-order functions - Code generation using tools like T4 - Dynamic languages using their meta-programming capabilities - Static weaving, by modifying the MSIL in a post-compilation process
  • #26: Dynamic proxies are supported in IoC frameworks such as Castle or Spring.net, and here’s a simple example of a logging interceptor that logs the entry and exit of a method and any unhandled exceptions that bubbles out of the method.
  • #29: If you are using a dependency injection framework already, and all you want is to be able to intercept method calls and inject additional behaviour, then dynamic proxies represent the easiest way for you to adopt AOP in your project right away. Also, some frameworks provide built-in aspects such as the logging aspect I showed you earlier. Most such frameworks also allow you to configure aspects through configuration files, making it easier for you to make changes in a live environment without having to compile and deploy any code changes.
  • #30: However, dynamic proxies only offer a limit set of AOP’s features, and if you’re not already using a dependency injection framework, adopting it into an existing code base will require a significant amount of work and change. There are also a number of restrictions, dynamic proxies do not work on static, or non-public methods, and they do not work on fields, properties or events. Since aspects are applied at runtime, there is a higher runtime overhead than there is with build-time AOP frameworks. However, this is only likely to cause a noticeable impact on your application’s performance if you’re generating large numbers of dynamic proxies. The bigger drawback is the lack of build-time verification to make sure that you’re using the aspects incorrectly. But for me, the biggest problem with using dynamic proxies is that it only works if your objects are instantiated using the container. This can cause major confusion to the consumers of your code, because when they instantiate the instances themselves the injected behaviours will not be present. That is not always clear, and without looking into your code and your container configuration it’ll be difficult to figure which behaviours were injected and which weren’t. This is one area where hard-to-detect bugs can creep in and you won’t see it until things blow up at runtime! Nasty stuff!
  • #31: Because IoC frameworks are so commonly used these days, and a lot people have their first experience with AOP through the use of dynamic proxies, many people have associated dependency injection with AOP. Well, I’m here to tell you that the two are not the same, at all! Dependency injection is a design pattern that addresses the problem of writing loosely-coupled components together, and helps you enforce the practice of design by contract. You program to an abstraction/interface rather than an implementation, and instead rely on the container to provide the concrete implementation at runtime. AOP on the other hand, addresses a very different issue: cross-cutting concerns as I showcased earlier. Dependency injection became associated with AOP because it just happens to be in a convenient place to allow users to inject new behaviours to existing code base transparently.
  • #34: That is the essence of the memoization technique, which I’ll show you right here with this bit of F# code. Don’t worry about the syntax; the important thing to note here is that this function takes another function as input, and use a dictionary to cache results before returning a modified version of the original function. …DEMO…   The memoize function is simple and yet effective, however, it breaks down when you use it with a recursive function. It’s not hard to fix it, but the whole AOP experience here is just not quite transparent and unobtrusive as you’d like.
  • #35: The advantage of doing AOP in functional programming is that you don’t require any external dependencies as you do with dynamic proxies and static weaving, instead you write everything as higher-order functions in the language you’re already familiar with.
  • #36: But, as I have demonstrated with recursive function, if you want to use the memoized version of the function f everywhere in your code, you’ll need to modify all the places where f is being used. Also, there’s no support for matching rules that lets you apply the same aspect to multiple functions in bulk. And when you want compose different aspects together, i.e. combining multiple higher-order functions, you’ll need to do it manually which is a task that’s easier said than done.
  • #48: A static weaving solution AOP usually involve a three phase implementation: Aspectual decomposition – based on requirements, identify concerns as either primary (problem domain) and cross-cutting Concern implementation – code each concern separately, primary (OO) and cross-cutting (AO) Aspectual recomposition – use aspect weaver to weave the separately implemented code together into a final system