SlideShare a Scribd company logo
Introduction to AOP

Dror Helper
@dhelper
About.Me
   Software developer and technical lead

   PostSharp MVP

   Blogger: http://blog.drorhelper.com
Developer write code
void transfer(Account fromAcc, Account toAcc, int amount)
{
      if (fromAcc.getBalance() < amount)
      {
             throw new InsufficientFundsException();
      }


      fromAcc.withdraw(amount);
      toAcc.deposit(amount);
}
Permission support – Right away!
void transfer(Account fromAcc, Account toAcc, int amount, User user)
{
       if (! checkUserPermission(user))
       {
                throw new UnauthorizedUserException();
       }


       if (fromAcc.getBalance() < amount)
       {
                throw new InsufficientFundsException();
       }


       fromAcc.withdraw(amount);
       toAcc.deposit(amount);
}
Need to check parameters – Done!
void transfer(Account fromAcc, Account toAcc, int amount, User user)
{
          if(fromAcc == null || toAcc == null)
          {
                      throw new IllegalArgumentException ();
          }


          if(balance <= 0)
          {
                      throw new IllegalArgumentException ();
          }


          if (! checkUserPermission(user))
          {
                      throw new UnauthorizedUserException();
          }


          if (fromAcc.getBalance() < amount)
          {
                      throw new InsufficientFundsException();
          }


          fromAcc.withdraw(amount);
          toAcc.deposit(amount);
}
Needs logging – no problems!
void transfer(Account fromAcc, Account toAcc, int amount, User user)
{
        logger.info("transferring money...");
        if(balance <= 0)
        {
                   throw new IllegalArgumentException ();
        }


        if (! checkUserPermission(user))
        {
                  logger.info("User has no permission.");
                  throw new UnauthorizedUserException();
        }


        if (fromAcc.getBalance() < amount)
        {
                  logger.info("Insufficient Funds, sorry");
                  throw new InsufficientFundsException();
        }


        fromAcc.withdraw(amount);
        toAcc.deposit(amount);
And finally – exception handling
void transfer(Account fromAcc, Account toAcc, int amount, User user)
{
             logger.info("transferring money...");
             if(balance <= 0)
             {
                                throw new IllegalArgumentException ();
             }


             if (! checkUserPermission(user))
             {
                            logger.info("User has no permission.");
                            throw new UnauthorizedUserException();
             }


             if (fromAcc.getBalance() < amount)
             {
                            logger.info("Insufficient Funds, sorry");
                            throw new InsufficientFundsException();
             }
             try
             {
                            fromAcc.withdraw(amount);
                            toAcc.deposit(amount);
             }
             catch(Exception exc)
             {
                            logger.info(“failed transaction.");
                            return;
             }
What can we do?
The Problem
   Code duplication

   Hard to read

   Difficult to maintain

   Not all programmers code the same


             Ctrl + C, Ctrl + V
Problem - Cross cutting concerns


                Customer   Product    Order




                           Logging


Cross-Cutting
                           Security
Concerns


                           Caching
Non-Functional Requirements
   Security
   Caching
   Tracing
   Exception handling
   Monitoring
   Validation
   Persistence
   Transactions
   Thread sync
Solution  AOP
    Separation of concerns
    Extension of OOP

1.    Encapsulate Cross cutting concerns into aspects
2.    Apply aspects to code
Why AOP


              • AOP exist for more then 15
   Mature       years

   Industry   • Industry standard
   adopted
  Observed    • -15% lines of code
  Benefits    • -20% decoupling
Terminology
Join Point
static void Main()
{
                                          myClass1.Func1
          var myClass1 = new MyClass();

          var myClass2 = new MyClass();



          myClass1.Func1();
          myClass1.Func2(2, 3);
                                          myClass1.Func2
          myClass2.Func2(4, 5);
}




                                          myClass2.Func2
Point Cuts

             myClass1.Func1




             myClass1.Func2   Before Func2




             myClass2.Func2
Advice
   The code to run
   Typically small
   Injected at join point
Aspect
Join Point + Advice = Aspect
How to “do” AOP
Our example for today – the calculator
My co-worker solution
#1 Functional programming
   Using higher order functions to “warp” existing code
   Decorator pattern
1# Functional Programming

              +                                -
   No additional                  You cannot automatically
    dependency in your              pass context from the
                                    caller to the aspect code
    build or runtime code.
                                   Must modify the code of
   Programmers are                 every method to which
    already familiar with the       you want to add the
    technology.                     aspect.

                                   Aspect composition is less
                                    convenient.
Why not use existing tools
What IoC containers can do for you?
   Enable Dependency Injection (DI)

   Create objects and satisfy it’s dependencies

   A lot more..
#2 Dynamic proxies




                      Framework


Application   Proxy               Aspect   Object
.NET IoC tools
   Unity http://unity.codeplex.com/
   Spring.NET http://www.springframework.net/
   Castle http://www.castleproject.org/
Dynamic proxies

              +                                -
   You may already be           Very limited aspect-oriented
                                  features.
    using a DI framework.
                                 Your objects must be
                                  instantiated using the
   Aspects can be                container
    configured after build.
                                 Does not work on
                                  static, non-public, and/or
   Some aspects may be           non-virtual methods
    provided by the
                                 Does not work on
    framework.                    fields, properties, or events.
#3 MSIL transformations




                       IL        Final
   Code    Compile
                     weaving   Assembly
IL transformation tools
   Mono.Cecil http://www.mono-project.com/Cecil
   NotifyPropertyWeaver
    http://code.google.com/p/notifypropertyweaver/
MSIL transformations

             +                              -
   Very powerful. You can      Requires an advanced
                                 knowledge of MSIL.
    achieve virtually any
    code transformation         Very low level

   These frameworks are        typically do not compose
                                 well when many are
    free of charge and           applied to the same
    backed by large              method.
    companies.
                                No Visual Studio tooling.
#4 Build time AOP


                Build Process
                     Intermediate
                                            Final
Source    Compiler     Assembly     AOP   Assembly
 Code                     (IL)




Aspects
Summery
 Use AOP because:

   Less code = fewer bugs
   Less code = easier to read and maintain
   Reduce duplicate code
   Improve team work/architecture
   Reduce development cost
Resources
Cross Cutting Concerns blog
http://crosscuttingconcerns.com/

My blog: http://blog.drorhelper.com

More Related Content

PDF
Spring AOP
PPTX
Spring AOP Introduction
PPTX
Spring AOP in Nutshell
PDF
Reactive Thinking in Java with RxJava2
PDF
JavaFX Pitfalls
PDF
Intro to JavaScript
PPTX
Spring aop concepts
PDF
DataFX 8 (JavaOne 2014)
Spring AOP
Spring AOP Introduction
Spring AOP in Nutshell
Reactive Thinking in Java with RxJava2
JavaFX Pitfalls
Intro to JavaScript
Spring aop concepts
DataFX 8 (JavaOne 2014)

What's hot (20)

PDF
Apex 5 plugins for everyone version 2018
PDF
Dart for Java Developers
PPTX
Zend Studio Tips and Tricks
PDF
Test Driven Development with JavaFX
PDF
Living With Legacy Code
PPTX
Testing React Applications
PDF
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
PDF
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
PDF
Stanfy MadCode Meetup #11: Why do you need to switch from Obj-C to Swift, or ...
PPTX
Frontend training
PDF
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
PDF
The Art of Unit Testing - Towards a Testable Design
PDF
CBDW2014 - MockBox, get ready to mock your socks off!
PDF
JavaOne - The JavaFX Community and Ecosystem
PDF
RESTful services and OAUTH protocol in IoT
PDF
Pharo Optimising JIT Internals
ODP
Angularjs
PDF
How AngularJS Embraced Traditional Design Patterns
PPTX
Dependency injection - the right way
PDF
How Testability Inspires AngularJS Design / Ran Mizrahi
Apex 5 plugins for everyone version 2018
Dart for Java Developers
Zend Studio Tips and Tricks
Test Driven Development with JavaFX
Living With Legacy Code
Testing React Applications
Java Hurdling: Obstacles and Techniques in Java Client Penetration-Testing
Universal JavaScript Web Applications with React - Luciano Mammino - Codemoti...
Stanfy MadCode Meetup #11: Why do you need to switch from Obj-C to Swift, or ...
Frontend training
Evolving a Clean, Pragmatic Architecture - A Craftsman's Guide
The Art of Unit Testing - Towards a Testable Design
CBDW2014 - MockBox, get ready to mock your socks off!
JavaOne - The JavaFX Community and Ecosystem
RESTful services and OAUTH protocol in IoT
Pharo Optimising JIT Internals
Angularjs
How AngularJS Embraced Traditional Design Patterns
Dependency injection - the right way
How Testability Inspires AngularJS Design / Ran Mizrahi
Ad

Similar to Introduction to aop (20)

PPTX
06.1 .Net memory management
PPTX
Common ASP.NET Design Patterns - Telerik India DevCon 2013
PDF
10 Typical Problems in Enterprise Java Applications
PPTX
Object Oriented Software Development revision slide
PDF
Epic.NET: Processes, patterns and architectures
PPTX
Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...
PDF
Aspect Oriented Programming and MVC with Spring Framework
PPTX
AOP in C# 2013
PDF
10 Typical Enterprise Java Problems
PDF
Synthesizing API Usage Examples
PDF
MS.NET Training
PDF
"An introduction to object-oriented programming for those who have never done...
PPTX
Real Object-Oriented Programming: Empirically Validated Benefits of the DCI P...
PDF
Clean code
PPTX
Oop concepts
PPTX
Introduction to Aspect Oriented Programming (DDD South West 4.0)
PDF
10 Ways To Improve Your Code
PDF
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
PPTX
Intro To AOP
PPTX
Writing clean code in C# and .NET
06.1 .Net memory management
Common ASP.NET Design Patterns - Telerik India DevCon 2013
10 Typical Problems in Enterprise Java Applications
Object Oriented Software Development revision slide
Epic.NET: Processes, patterns and architectures
Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...
Aspect Oriented Programming and MVC with Spring Framework
AOP in C# 2013
10 Typical Enterprise Java Problems
Synthesizing API Usage Examples
MS.NET Training
"An introduction to object-oriented programming for those who have never done...
Real Object-Oriented Programming: Empirically Validated Benefits of the DCI P...
Clean code
Oop concepts
Introduction to Aspect Oriented Programming (DDD South West 4.0)
10 Ways To Improve Your Code
SeaJUG Dec 2001: Aspect-Oriented Programming with AspectJ
Intro To AOP
Writing clean code in C# and .NET
Ad

More from Dror Helper (20)

PPTX
Unit testing patterns for concurrent code
PPTX
The secret unit testing tools no one ever told you about
PPTX
Debugging with visual studio beyond 'F5'
PPTX
From clever code to better code
PPTX
From clever code to better code
PPTX
A software developer guide to working with aws
PPTX
The secret unit testing tools no one has ever told you about
PPTX
The role of the architect in agile
PDF
Harnessing the power of aws using dot net core
PPTX
Developing multi-platform microservices using .NET core
PPTX
Harnessing the power of aws using dot net
PPTX
Secret unit testing tools no one ever told you about
PPTX
C++ Unit testing - the good, the bad & the ugly
PPTX
Working with c++ legacy code
PPTX
Visual Studio tricks every dot net developer should know
PPTX
Secret unit testing tools
PPTX
Electronics 101 for software developers
PPTX
Navigating the xDD Alphabet Soup
PPTX
Building unit tests correctly
PPTX
Who’s afraid of WinDbg
Unit testing patterns for concurrent code
The secret unit testing tools no one ever told you about
Debugging with visual studio beyond 'F5'
From clever code to better code
From clever code to better code
A software developer guide to working with aws
The secret unit testing tools no one has ever told you about
The role of the architect in agile
Harnessing the power of aws using dot net core
Developing multi-platform microservices using .NET core
Harnessing the power of aws using dot net
Secret unit testing tools no one ever told you about
C++ Unit testing - the good, the bad & the ugly
Working with c++ legacy code
Visual Studio tricks every dot net developer should know
Secret unit testing tools
Electronics 101 for software developers
Navigating the xDD Alphabet Soup
Building unit tests correctly
Who’s afraid of WinDbg

Recently uploaded (20)

PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Agricultural_Statistics_at_a_Glance_2022_0.pdf
PPTX
20250228 LYD VKU AI Blended-Learning.pptx
PDF
Reach Out and Touch Someone: Haptics and Empathic Computing
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PPT
Teaching material agriculture food technology
PDF
Encapsulation theory and applications.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
Cloud computing and distributed systems.
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PPTX
sap open course for s4hana steps from ECC to s4
PDF
The Rise and Fall of 3GPP – Time for a Sabbatical?
PDF
Machine learning based COVID-19 study performance prediction
PDF
Chapter 3 Spatial Domain Image Processing.pdf
PDF
Electronic commerce courselecture one. Pdf
PDF
NewMind AI Weekly Chronicles - August'25 Week I
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Understanding_Digital_Forensics_Presentation.pptx
VMware vSphere Foundation How to Sell Presentation-Ver1.4-2-14-2024.pptx
Spectral efficient network and resource selection model in 5G networks
Agricultural_Statistics_at_a_Glance_2022_0.pdf
20250228 LYD VKU AI Blended-Learning.pptx
Reach Out and Touch Someone: Haptics and Empathic Computing
“AI and Expert System Decision Support & Business Intelligence Systems”
Teaching material agriculture food technology
Encapsulation theory and applications.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
sap open course for s4hana steps from ECC to s4
The Rise and Fall of 3GPP – Time for a Sabbatical?
Machine learning based COVID-19 study performance prediction
Chapter 3 Spatial Domain Image Processing.pdf
Electronic commerce courselecture one. Pdf
NewMind AI Weekly Chronicles - August'25 Week I
Build a system with the filesystem maintained by OSTree @ COSCUP 2025

Introduction to aop

  • 1. Introduction to AOP Dror Helper @dhelper
  • 2. About.Me  Software developer and technical lead  PostSharp MVP  Blogger: http://blog.drorhelper.com
  • 3. Developer write code void transfer(Account fromAcc, Account toAcc, int amount) { if (fromAcc.getBalance() < amount) { throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); }
  • 4. Permission support – Right away! void transfer(Account fromAcc, Account toAcc, int amount, User user) { if (! checkUserPermission(user)) { throw new UnauthorizedUserException(); } if (fromAcc.getBalance() < amount) { throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); }
  • 5. Need to check parameters – Done! void transfer(Account fromAcc, Account toAcc, int amount, User user) { if(fromAcc == null || toAcc == null) { throw new IllegalArgumentException (); } if(balance <= 0) { throw new IllegalArgumentException (); } if (! checkUserPermission(user)) { throw new UnauthorizedUserException(); } if (fromAcc.getBalance() < amount) { throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount); }
  • 6. Needs logging – no problems! void transfer(Account fromAcc, Account toAcc, int amount, User user) { logger.info("transferring money..."); if(balance <= 0) { throw new IllegalArgumentException (); } if (! checkUserPermission(user)) { logger.info("User has no permission."); throw new UnauthorizedUserException(); } if (fromAcc.getBalance() < amount) { logger.info("Insufficient Funds, sorry"); throw new InsufficientFundsException(); } fromAcc.withdraw(amount); toAcc.deposit(amount);
  • 7. And finally – exception handling void transfer(Account fromAcc, Account toAcc, int amount, User user) { logger.info("transferring money..."); if(balance <= 0) { throw new IllegalArgumentException (); } if (! checkUserPermission(user)) { logger.info("User has no permission."); throw new UnauthorizedUserException(); } if (fromAcc.getBalance() < amount) { logger.info("Insufficient Funds, sorry"); throw new InsufficientFundsException(); } try { fromAcc.withdraw(amount); toAcc.deposit(amount); } catch(Exception exc) { logger.info(“failed transaction."); return; }
  • 9. The Problem  Code duplication  Hard to read  Difficult to maintain  Not all programmers code the same Ctrl + C, Ctrl + V
  • 10. Problem - Cross cutting concerns Customer Product Order Logging Cross-Cutting Security Concerns Caching
  • 11. Non-Functional Requirements  Security  Caching  Tracing  Exception handling  Monitoring  Validation  Persistence  Transactions  Thread sync
  • 12. Solution  AOP  Separation of concerns  Extension of OOP 1. Encapsulate Cross cutting concerns into aspects 2. Apply aspects to code
  • 13. Why AOP • AOP exist for more then 15 Mature years Industry • Industry standard adopted Observed • -15% lines of code Benefits • -20% decoupling
  • 15. Join Point static void Main() { myClass1.Func1 var myClass1 = new MyClass(); var myClass2 = new MyClass(); myClass1.Func1(); myClass1.Func2(2, 3); myClass1.Func2 myClass2.Func2(4, 5); } myClass2.Func2
  • 16. Point Cuts myClass1.Func1 myClass1.Func2 Before Func2 myClass2.Func2
  • 17. Advice  The code to run  Typically small  Injected at join point
  • 18. Aspect Join Point + Advice = Aspect
  • 20. Our example for today – the calculator
  • 22. #1 Functional programming  Using higher order functions to “warp” existing code  Decorator pattern
  • 23. 1# Functional Programming + -  No additional  You cannot automatically dependency in your pass context from the caller to the aspect code build or runtime code.  Must modify the code of  Programmers are every method to which already familiar with the you want to add the technology. aspect.  Aspect composition is less convenient.
  • 24. Why not use existing tools
  • 25. What IoC containers can do for you?  Enable Dependency Injection (DI)  Create objects and satisfy it’s dependencies  A lot more..
  • 26. #2 Dynamic proxies Framework Application Proxy Aspect Object
  • 27. .NET IoC tools  Unity http://unity.codeplex.com/  Spring.NET http://www.springframework.net/  Castle http://www.castleproject.org/
  • 28. Dynamic proxies + -  You may already be  Very limited aspect-oriented features. using a DI framework.  Your objects must be instantiated using the  Aspects can be container configured after build.  Does not work on static, non-public, and/or  Some aspects may be non-virtual methods provided by the  Does not work on framework. fields, properties, or events.
  • 29. #3 MSIL transformations IL Final Code Compile weaving Assembly
  • 30. IL transformation tools  Mono.Cecil http://www.mono-project.com/Cecil  NotifyPropertyWeaver http://code.google.com/p/notifypropertyweaver/
  • 31. MSIL transformations + -  Very powerful. You can  Requires an advanced knowledge of MSIL. achieve virtually any code transformation  Very low level  These frameworks are  typically do not compose well when many are free of charge and applied to the same backed by large method. companies.  No Visual Studio tooling.
  • 32. #4 Build time AOP Build Process Intermediate Final Source Compiler Assembly AOP Assembly Code (IL) Aspects
  • 33. Summery Use AOP because:  Less code = fewer bugs  Less code = easier to read and maintain  Reduce duplicate code  Improve team work/architecture  Reduce development cost
  • 34. Resources Cross Cutting Concerns blog http://crosscuttingconcerns.com/ My blog: http://blog.drorhelper.com

Editor's Notes

  • #11: Non functional requirments
  • #16: A call to a methodThe method’s executionAssignment to a variableReturn statementObject constructionConditional checkComparisonException handlerLoops
  • #17: A group of Join pointFilter drivenAttribute driven
  • #25: IoC containers
  • #27: Using IoC containers
  • #30: Add IL in compile timeDifficult and fragile“Mini AOPs”
  • #33: Adding step to compilationUsing IL weavingShow diagram