SlideShare a Scribd company logo
An Introduction to Aspect-Oriented Programming in Microsoft .NET. Produce Cleaner Code with Aspect-Oriented Programming Gaël Fraiteur gael@sharpcrafters.comhttp://www.sharpcrafters.com/
AOP Facts
Featured PostSharp Customers
Agenda The Problem with Conventional Programming What is AOP? Why AOP? PostSharp Features Comparing AOP Frameworks
The Problem with Conventional Programming Part 1
In the beginning           there was nothing. publicclassCustomerProcesses { }
Customer said: let there be business value. publicclassCustomerProcesses { publicvoid RentBook( int bookId, int customerId )     { Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId );           book.RentedTo = customer;         customer.AccountLines.Add(string.Format( "Rental of book {0}.", book ), book.RentalPrice );         customer.Balance -= book.RentalPrice;     } } And there was business code.
internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource( typeof (CustomerProcesses).FullName );   publicvoid RentBook( int bookId, int customerId )     {        trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0},             customerId = {1} )",             bookId, customerId ); try{              Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId );               book.RentedTo = customer;             customer.AccountLines.Add( string.Format( "Rental of book {0}.", book ), book.RentalPrice );             customer.Balance -= book.RentalPrice;             trace.TraceInformation(               "Leaving CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )",               bookId, customerId );         }         catch ( Exception e )         {             trace.TraceEvent( TraceEventType.Error, 0,                               "Exception: CustomerProcesses.CreateCustomer(                               bookId = {0}, customerId = {1} ) failed : {2}",                               bookId, customerId, e.Message );              throw;         }     } } Testers said: Letthere be logging And there was logging code.
internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource(typeof(CustomerProcesses).FullName);   publicvoid RentBook(int bookId, int customerId)     { if (bookId <= 0) thrownewArgumentOutOfRangeException("bookId"); if (customerId <= 0) thrownewArgumentOutOfRangeException("customerId");           trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )",             bookId, customerId);   try         { Book book = Book.GetById(bookId); Customer customer = Customer.GetById(customerId);               book.RentedTo = customer;             customer.AccountLines.Add(string.Format("Rental of book {0}.", book),                                      book.RentalPrice);             customer.Balance -= book.RentalPrice;               trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer( bookId = {0},                 customerId = {1} )“,  bookId, customerId);         } catch (Exception e)         {             trace.TraceEvent(TraceEventType.Error, 0,                    "Exception: CustomerProcesses.CreateCustomer( bookId = {0},                     customerId = {1} ) failed : {2}",                     bookId, customerId, e.Message); throw;         }     } } Devssaid: Letthere be defensive programming Thenthere was precondition checking code.
internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource(typeof(CustomerProcesses).FullName);   publicvoid RentBook(int bookId, int customerId)     { if (bookId <= 0) thrownewArgumentOutOfRangeException("bookId"); if (customerId <= 0) thrownewArgumentOutOfRangeException("customerId");           trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0},            customerId = {1} )“,  bookId, customerId);   try         { for (int i = 0; ; i++)             { try                 { using (var ts = newTransactionScope())                     { Book book = Book.GetById(bookId); Customer customer = Customer.GetById(customerId);                           book.RentedTo = customer;                         customer.AccountLines.Add(string.Format("Rental of book {0}.", book),                          book.RentalPrice);                         customer.Balance -= book.RentalPrice;                           ts.Complete();                     }   break;                 } catch (TransactionConflictException)                 { if (i < 3) continue; else throw;                 }             }               trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer(                bookId = {0}, customerId = {1} )",                 bookId, customerId);         } catch (Exception e)         {             trace.TraceEvent(TraceEventType.Error, 0, "Exception: CustomerProcesses.CreateCustomer( bookId = {0},              customerId = {1} ) failed : {2}",               bookId, customerId, e.Message); throw;         }     } } Let there be safe concurrent execution. And there was transaction handling code.
internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource(typeof(CustomerProcesses).FullName);   publicvoid RentBook(int bookId, int customerId)     { if (bookId <= 0) thrownewArgumentOutOfRangeException("bookId"); if (customerId <= 0) thrownewArgumentOutOfRangeException("customerId");   try         {             trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer(                  bookId = {0}, customerId = {1} )",                 bookId, customerId );   try             { for ( int i = 0;; i++ )                 { try                     { using ( var ts = newTransactionScope() )                         { Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId );                               book.RentedTo = customer;                             customer.AccountLines.Add( string.Format( "Rental of book {0}.", book ),                               book.RentalPrice );                             customer.Balance -= book.RentalPrice;                               ts.Complete();                         }   break;                     } catch ( TransactionConflictException )                     { if ( i < 3 ) continue; else throw;                     }                 }                   trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer(                     bookId = {0}, customerId = {1} )",                     bookId, customerId );             } catch ( Exception e )             {                 trace.TraceEvent( TraceEventType.Error, 0, "Exception: CustomerProcesses.CreateCustomer(                   bookId = {0}, customerId = {1} ) failed : {2}",                                   bookId, customerId, e.Message ); throw;             }         } catch ( Exception e )         { if (ExceptionManager.Handle(e)) throw;         }     } } Let there be user-friendly error messages. And there was exception handling code.
AKSEL BACHMEIER architect YOHJI YAMAMOTOcustomer
We want a nice separation of concerns (assembly > namespace > class > method) OOP forces us to write crap! Code Scattering Code Tangling Code Coupling Layer 1 Layer 2 Why do we write ugly code?
Security Exception Handling Tracing Monitoring Transaction Data Binding Thread Sync Caching Validation Non-Functional Requirements Cross-Cutting Concerns
We have patterns. How to implement them? Template-Based Code Generators Anonymous Methods (Functional Programming) Object-Oriented Alternatives
Encapsulating Infrastructure Concerns?
Aspects!
Strengthen Applications With Aspects Show Me!
Show Me! 1. Add a reference to PostSharp.dll
Show Me! 2. Write an aspect
Show Me! 3. Apply the aspect
Show Me! How does it work? 1. Source 2. Compiler 3. PostSharp 4. Run Time
The Idea Behind AOP Part 3
Problem Domain Cross-Cutting Concerns Solution Domain Separation of Concerns
What is AOP? An extension of (not an alternative to) OOP that addresses the issue of cross-cutting concerns by providing a mean to: Encapsulate cross-cutting concerns into Aspects = collection of transformations of code Applyaspects to elements of code
15 Years of AOP History Hype Years Productivity Years Research Years
Why You Should Care The benefits of aspect-oriented programming
The benefits of aspect-oriented programming Decrease Development Costs WriteFewer lines of code ReadFewer lines of code	 Concise, clear, understandable code Size-Cost relationship is superlinear
The benefits of aspect-oriented programming Improve Quality Fewer lines of code	-> Fewer Defects More automation	-> Fewer Defects Less boiler-plate code 	-> More interesting work 	-> Increased attention 	-> Fewer Defects
The benefits of aspect-oriented programming Decrease Maintenance Costs Remember:  Fewer Defects Maintenance = 75% Reading Code How do you change a pattern once it’s implemented? Better architecture metrics: Decreased component coupling Increased component cohesion
The benefits of aspect-oriented programming Decrease Maintenance Costs
The benefits of aspect-oriented programming Optimize Skillsets I understand provisioning processes better than anyone in this company, I master multithreading better than anyone on earth Picture © Darren Rogers and chatwoodsfp (Flicker)
Features
Features Code Transformation Primitives Modifications Introductions Around Methods Method Interception Property Interception Field Interception Event Interception Interface Introduction Method Introduction Property Introduction Event Introduction Member Import Custom Attribute Intro Managed Resource Intro
Features Composite Aspects Aspects composed of multiple primitive transformations Advice = Additional Behavior ≈ Transformation Pointcut = Expression selecting target elements of code Declarative LINQ over System.Reflection Adding aspects dynamically: IAspectProvider
Features Aspect Multicasting Using a single line of code, apply an aspects to multiple elements of code based on: Attributes (public/private, virtual/sealed, …) Naming conventions
Features Attribute Inheritance Interfaces Classes Virtual Methods Assemblies (!) - or -
Robust Aspect Composition Multiple aspects on the same element of code Aspect dependency framework Ordering Requirement Conflict Strong ordering and commutativity  Deterministic Behavior D C B A
Visual Studio Extension 1. Code Adornment + Clickable Tooltips “What aspects are applied to a given element of code?” 1. Adornment + Tooltip Aspects Base Code Bi-Directional Navigation 2. Aspect Browser “Which elements of code is a given a given aspect applied to?” 2. Aspect Browser
Comparing Aspect Frameworks Part 4
Comparing Aspect Frameworks What to compare? Expressive Non-Invasive Supported Framework Robust Productive Dynamic
Build-Time MSIL Transformation Consumer Object Enhanced Object Aspects
AO Infrastructure Transparent Proxies Enhanced Object Consumer Object Transparent Proxy RealProxy Aspects The transparent proxy is type-compatible with the enhanced object(CLR-provided magic)
JIT-Emitted Proxy AO Infrastructure Consumer Object Proxy Enhanced Object Aspects The proxy implements an interface of the enhanced object.
JIT-Emitted Subclass AO Infrastructure Consumer Object Proxy Enhanced Object Aspects The proxy extends (inherits from) the enhanced object.
Comparing Aspect Frameworks Static vs Dynamic AOP Spring.NET Castle MS Unity/PIAB PostSharp LinFu Build-Time: Very Expressive Robust Model Not InvasiveStatic Run-Time:Less ExpressiveBrittle Model InvasiveDynamic Hybrid
Comparing Aspect Frameworks Expressiveness (1/2) What can you do with the framework?
Comparing Aspect Frameworks Expressiveness (2/2) How do you apply aspects to code?
Comparing Aspect Frameworks Non-Invasiveness Can you use aspects without deep refactoring? Require the use of factory methods
Comparing Aspect Frameworks Robustness Can you prevent aspects from being improperly used?
Comparing Aspect Frameworks Misc. Other points that matter
Comparing Aspect Frameworks My Own Summary Aspects on Service Boundaries: use your favorite application framework. Aspects on Ordinary and GUI Objects: use PostSharp. You can mix PostSharp with your favorite application framework!
Summary
We need Aspects!
We have great frameworks! and PostSharp happens to be the best in .NET :).
http://www.sharpcrafters.com/gael@sharpcrafters.com

More Related Content

Viewers also liked

Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
Yan Cui
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
Anumod Kumar
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
Jeroen Rosenberg
 
Apache Solr lessons learned
Apache Solr lessons learnedApache Solr lessons learned
Apache Solr lessons learned
Jeroen Rosenberg
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
Rodger Oates
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop concepts
RushiBShah
 
Aspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPAspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHP
William Candillon
 
Aspect Oriented Software Development
Aspect Oriented Software DevelopmentAspect Oriented Software Development
Aspect Oriented Software DevelopmentJignesh Patel
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
SHAKIL AKHTAR
 

Viewers also liked (9)

Introduction to Aspect Oriented Programming
Introduction to Aspect Oriented ProgrammingIntroduction to Aspect Oriented Programming
Introduction to Aspect Oriented Programming
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 
Apache Solr lessons learned
Apache Solr lessons learnedApache Solr lessons learned
Apache Solr lessons learned
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented Programming
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop concepts
 
Aspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPAspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHP
 
Aspect Oriented Software Development
Aspect Oriented Software DevelopmentAspect Oriented Software Development
Aspect Oriented Software Development
 
Spring AOP
Spring AOPSpring AOP
Spring AOP
 

Similar to Produce Cleaner Code with Aspect-Oriented Programming

Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...
Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...
Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...Zubair Ahmed
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
Juan Pablo
 
Project: Call Center Management
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Management
pritamkumar
 
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxSH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxMongoDB
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
MarcinStachniuk
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
PhilWinstanley
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
Nicolas Corrarello
 
Functional DDD
Functional DDDFunctional DDD
Functional DDD
Alessandro Melchiori
 
Introduction to trader bots with Python
Introduction to trader bots with PythonIntroduction to trader bots with Python
Introduction to trader bots with Python
roskakori
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptdominion
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
명신 김
 
Redux Action Creators
Redux Action CreatorsRedux Action Creators
Redux Action Creators
Konstantins Starovoitovs
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
Richard Dingwall
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
greenwop
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
DrDhivyaaCRAssistant
 
Improving Correctness with Types
Improving Correctness with TypesImproving Correctness with Types
Improving Correctness with Types
Iain Hull
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
Ajay Khatri
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
Srikanth Shreenivas
 

Similar to Produce Cleaner Code with Aspect-Oriented Programming (20)

Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...
Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...
Introduction to Aspect Oriented Programming in .NET with PostSharp by Zubair ...
 
Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#Lo Mejor Del Pdc2008 El Futrode C#
Lo Mejor Del Pdc2008 El Futrode C#
 
Project: Call Center Management
Project: Call Center ManagementProject: Call Center Management
Project: Call Center Management
 
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptxSH 1 - SES 8 - Stitch_Overview_TLV.pptx
SH 1 - SES 8 - Stitch_Overview_TLV.pptx
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
 
GraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learnedGraphQL - when REST API is not enough - lessons learned
GraphQL - when REST API is not enough - lessons learned
 
Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0Policy Injection in ASP.NET using Enterprise Library 3.0
Policy Injection in ASP.NET using Enterprise Library 3.0
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin Infrastructure
 
Functional DDD
Functional DDDFunctional DDD
Functional DDD
 
Introduction to trader bots with Python
Introduction to trader bots with PythonIntroduction to trader bots with Python
Introduction to trader bots with Python
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScript
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴
 
Rhino Mocks
Rhino MocksRhino Mocks
Rhino Mocks
 
Redux Action Creators
Redux Action CreatorsRedux Action Creators
Redux Action Creators
 
Domain Driven Design 101
Domain Driven Design 101Domain Driven Design 101
Domain Driven Design 101
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
UNIT 1 (7).pptx
UNIT 1 (7).pptxUNIT 1 (7).pptx
UNIT 1 (7).pptx
 
Improving Correctness with Types
Improving Correctness with TypesImproving Correctness with Types
Improving Correctness with Types
 
Basics of Java Script (JS)
Basics of Java Script (JS)Basics of Java Script (JS)
Basics of Java Script (JS)
 
Practices For Becoming A Better Programmer
Practices For Becoming A Better ProgrammerPractices For Becoming A Better Programmer
Practices For Becoming A Better Programmer
 

More from PostSharp Technologies

Advanced Defensive Coding Techniques (with Introduction to Design by Contract)
Advanced Defensive Coding Techniques (with Introduction to Design by Contract)Advanced Defensive Coding Techniques (with Introduction to Design by Contract)
Advanced Defensive Coding Techniques (with Introduction to Design by Contract)
PostSharp Technologies
 
Applying Object Composition to Build Rich Domain Models
Applying Object Composition to Build Rich Domain ModelsApplying Object Composition to Build Rich Domain Models
Applying Object Composition to Build Rich Domain Models
PostSharp Technologies
 
Performance is a Feature!
Performance is a Feature!Performance is a Feature!
Performance is a Feature!
PostSharp Technologies
 
Building Better Architecture with UX-Driven Design
Building Better Architecture with UX-Driven DesignBuilding Better Architecture with UX-Driven Design
Building Better Architecture with UX-Driven Design
PostSharp Technologies
 
Solving Localization Challenges with Design Pattern Automation
Solving Localization Challenges with Design Pattern AutomationSolving Localization Challenges with Design Pattern Automation
Solving Localization Challenges with Design Pattern Automation
PostSharp Technologies
 
Applying a Methodical Approach to Website Performance
Applying a Methodical Approach to Website PerformanceApplying a Methodical Approach to Website Performance
Applying a Methodical Approach to Website Performance
PostSharp Technologies
 
10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming
PostSharp Technologies
 
Multithreading Fundamentals
Multithreading FundamentalsMultithreading Fundamentals
Multithreading Fundamentals
PostSharp Technologies
 
Multithreading Design Patterns
Multithreading Design PatternsMultithreading Design Patterns
Multithreading Design Patterns
PostSharp Technologies
 
Design Pattern Automation
Design Pattern AutomationDesign Pattern Automation
Design Pattern Automation
PostSharp Technologies
 

More from PostSharp Technologies (10)

Advanced Defensive Coding Techniques (with Introduction to Design by Contract)
Advanced Defensive Coding Techniques (with Introduction to Design by Contract)Advanced Defensive Coding Techniques (with Introduction to Design by Contract)
Advanced Defensive Coding Techniques (with Introduction to Design by Contract)
 
Applying Object Composition to Build Rich Domain Models
Applying Object Composition to Build Rich Domain ModelsApplying Object Composition to Build Rich Domain Models
Applying Object Composition to Build Rich Domain Models
 
Performance is a Feature!
Performance is a Feature!Performance is a Feature!
Performance is a Feature!
 
Building Better Architecture with UX-Driven Design
Building Better Architecture with UX-Driven DesignBuilding Better Architecture with UX-Driven Design
Building Better Architecture with UX-Driven Design
 
Solving Localization Challenges with Design Pattern Automation
Solving Localization Challenges with Design Pattern AutomationSolving Localization Challenges with Design Pattern Automation
Solving Localization Challenges with Design Pattern Automation
 
Applying a Methodical Approach to Website Performance
Applying a Methodical Approach to Website PerformanceApplying a Methodical Approach to Website Performance
Applying a Methodical Approach to Website Performance
 
10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming10 Reasons You MUST Consider Pattern-Aware Programming
10 Reasons You MUST Consider Pattern-Aware Programming
 
Multithreading Fundamentals
Multithreading FundamentalsMultithreading Fundamentals
Multithreading Fundamentals
 
Multithreading Design Patterns
Multithreading Design PatternsMultithreading Design Patterns
Multithreading Design Patterns
 
Design Pattern Automation
Design Pattern AutomationDesign Pattern Automation
Design Pattern Automation
 

Recently uploaded

Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
RinaMondal9
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
Alpen-Adria-Universität
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
Prayukth K V
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
ControlCase
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
KAMESHS29
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 

Recently uploaded (20)

Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Free Complete Python - A step towards Data Science
Free Complete Python - A step towards Data ScienceFree Complete Python - A step towards Data Science
Free Complete Python - A step towards Data Science
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 
Video Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the FutureVideo Streaming: Then, Now, and in the Future
Video Streaming: Then, Now, and in the Future
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 previewState of ICS and IoT Cyber Threat Landscape Report 2024 preview
State of ICS and IoT Cyber Threat Landscape Report 2024 preview
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
PCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase TeamPCI PIN Basics Webinar from the Controlcase Team
PCI PIN Basics Webinar from the Controlcase Team
 
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
RESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for studentsRESUME BUILDER APPLICATION Project for students
RESUME BUILDER APPLICATION Project for students
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 

Produce Cleaner Code with Aspect-Oriented Programming

  • 1. An Introduction to Aspect-Oriented Programming in Microsoft .NET. Produce Cleaner Code with Aspect-Oriented Programming Gaël Fraiteur gael@sharpcrafters.comhttp://www.sharpcrafters.com/
  • 4. Agenda The Problem with Conventional Programming What is AOP? Why AOP? PostSharp Features Comparing AOP Frameworks
  • 5. The Problem with Conventional Programming Part 1
  • 6. In the beginning there was nothing. publicclassCustomerProcesses { }
  • 7. Customer said: let there be business value. publicclassCustomerProcesses { publicvoid RentBook( int bookId, int customerId ) { Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId );   book.RentedTo = customer; customer.AccountLines.Add(string.Format( "Rental of book {0}.", book ), book.RentalPrice ); customer.Balance -= book.RentalPrice; } } And there was business code.
  • 8. internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource( typeof (CustomerProcesses).FullName );   publicvoid RentBook( int bookId, int customerId ) { trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId ); try{  Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId );   book.RentedTo = customer; customer.AccountLines.Add( string.Format( "Rental of book {0}.", book ), book.RentalPrice ); customer.Balance -= book.RentalPrice; trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId ); } catch ( Exception e ) { trace.TraceEvent( TraceEventType.Error, 0, "Exception: CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} ) failed : {2}", bookId, customerId, e.Message ); throw; }   } } Testers said: Letthere be logging And there was logging code.
  • 9. internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource(typeof(CustomerProcesses).FullName);   publicvoid RentBook(int bookId, int customerId) { if (bookId <= 0) thrownewArgumentOutOfRangeException("bookId"); if (customerId <= 0) thrownewArgumentOutOfRangeException("customerId");   trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId);   try { Book book = Book.GetById(bookId); Customer customer = Customer.GetById(customerId);   book.RentedTo = customer; customer.AccountLines.Add(string.Format("Rental of book {0}.", book), book.RentalPrice); customer.Balance -= book.RentalPrice;   trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )“, bookId, customerId); } catch (Exception e) { trace.TraceEvent(TraceEventType.Error, 0, "Exception: CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} ) failed : {2}", bookId, customerId, e.Message); throw; } } } Devssaid: Letthere be defensive programming Thenthere was precondition checking code.
  • 10. internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource(typeof(CustomerProcesses).FullName);   publicvoid RentBook(int bookId, int customerId) { if (bookId <= 0) thrownewArgumentOutOfRangeException("bookId"); if (customerId <= 0) thrownewArgumentOutOfRangeException("customerId");   trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )“, bookId, customerId);   try { for (int i = 0; ; i++) { try { using (var ts = newTransactionScope()) { Book book = Book.GetById(bookId); Customer customer = Customer.GetById(customerId);   book.RentedTo = customer; customer.AccountLines.Add(string.Format("Rental of book {0}.", book), book.RentalPrice); customer.Balance -= book.RentalPrice;   ts.Complete(); }   break; } catch (TransactionConflictException) { if (i < 3) continue; else throw; } }   trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId); } catch (Exception e) { trace.TraceEvent(TraceEventType.Error, 0, "Exception: CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} ) failed : {2}", bookId, customerId, e.Message); throw; } } } Let there be safe concurrent execution. And there was transaction handling code.
  • 11. internalclassCustomerProcesses { privatestaticreadonlyTraceSource trace = newTraceSource(typeof(CustomerProcesses).FullName);   publicvoid RentBook(int bookId, int customerId) { if (bookId <= 0) thrownewArgumentOutOfRangeException("bookId"); if (customerId <= 0) thrownewArgumentOutOfRangeException("customerId");   try { trace.TraceInformation( "Entering CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId );   try { for ( int i = 0;; i++ ) { try { using ( var ts = newTransactionScope() ) { Book book = Book.GetById( bookId ); Customer customer = Customer.GetById( customerId );   book.RentedTo = customer; customer.AccountLines.Add( string.Format( "Rental of book {0}.", book ), book.RentalPrice ); customer.Balance -= book.RentalPrice;   ts.Complete(); }   break; } catch ( TransactionConflictException ) { if ( i < 3 ) continue; else throw; } }   trace.TraceInformation( "Leaving CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} )", bookId, customerId ); } catch ( Exception e ) { trace.TraceEvent( TraceEventType.Error, 0, "Exception: CustomerProcesses.CreateCustomer( bookId = {0}, customerId = {1} ) failed : {2}", bookId, customerId, e.Message ); throw; } } catch ( Exception e ) { if (ExceptionManager.Handle(e)) throw; } } } Let there be user-friendly error messages. And there was exception handling code.
  • 12. AKSEL BACHMEIER architect YOHJI YAMAMOTOcustomer
  • 13. We want a nice separation of concerns (assembly > namespace > class > method) OOP forces us to write crap! Code Scattering Code Tangling Code Coupling Layer 1 Layer 2 Why do we write ugly code?
  • 14. Security Exception Handling Tracing Monitoring Transaction Data Binding Thread Sync Caching Validation Non-Functional Requirements Cross-Cutting Concerns
  • 15. We have patterns. How to implement them? Template-Based Code Generators Anonymous Methods (Functional Programming) Object-Oriented Alternatives
  • 18. Strengthen Applications With Aspects Show Me!
  • 19. Show Me! 1. Add a reference to PostSharp.dll
  • 20. Show Me! 2. Write an aspect
  • 21. Show Me! 3. Apply the aspect
  • 22. Show Me! How does it work? 1. Source 2. Compiler 3. PostSharp 4. Run Time
  • 23. The Idea Behind AOP Part 3
  • 24. Problem Domain Cross-Cutting Concerns Solution Domain Separation of Concerns
  • 25. What is AOP? An extension of (not an alternative to) OOP that addresses the issue of cross-cutting concerns by providing a mean to: Encapsulate cross-cutting concerns into Aspects = collection of transformations of code Applyaspects to elements of code
  • 26. 15 Years of AOP History Hype Years Productivity Years Research Years
  • 27. Why You Should Care The benefits of aspect-oriented programming
  • 28. The benefits of aspect-oriented programming Decrease Development Costs WriteFewer lines of code ReadFewer lines of code Concise, clear, understandable code Size-Cost relationship is superlinear
  • 29. The benefits of aspect-oriented programming Improve Quality Fewer lines of code -> Fewer Defects More automation -> Fewer Defects Less boiler-plate code -> More interesting work -> Increased attention -> Fewer Defects
  • 30. The benefits of aspect-oriented programming Decrease Maintenance Costs Remember: Fewer Defects Maintenance = 75% Reading Code How do you change a pattern once it’s implemented? Better architecture metrics: Decreased component coupling Increased component cohesion
  • 31. The benefits of aspect-oriented programming Decrease Maintenance Costs
  • 32. The benefits of aspect-oriented programming Optimize Skillsets I understand provisioning processes better than anyone in this company, I master multithreading better than anyone on earth Picture © Darren Rogers and chatwoodsfp (Flicker)
  • 34. Features Code Transformation Primitives Modifications Introductions Around Methods Method Interception Property Interception Field Interception Event Interception Interface Introduction Method Introduction Property Introduction Event Introduction Member Import Custom Attribute Intro Managed Resource Intro
  • 35. Features Composite Aspects Aspects composed of multiple primitive transformations Advice = Additional Behavior ≈ Transformation Pointcut = Expression selecting target elements of code Declarative LINQ over System.Reflection Adding aspects dynamically: IAspectProvider
  • 36. Features Aspect Multicasting Using a single line of code, apply an aspects to multiple elements of code based on: Attributes (public/private, virtual/sealed, …) Naming conventions
  • 37. Features Attribute Inheritance Interfaces Classes Virtual Methods Assemblies (!) - or -
  • 38. Robust Aspect Composition Multiple aspects on the same element of code Aspect dependency framework Ordering Requirement Conflict Strong ordering and commutativity  Deterministic Behavior D C B A
  • 39. Visual Studio Extension 1. Code Adornment + Clickable Tooltips “What aspects are applied to a given element of code?” 1. Adornment + Tooltip Aspects Base Code Bi-Directional Navigation 2. Aspect Browser “Which elements of code is a given a given aspect applied to?” 2. Aspect Browser
  • 41. Comparing Aspect Frameworks What to compare? Expressive Non-Invasive Supported Framework Robust Productive Dynamic
  • 42. Build-Time MSIL Transformation Consumer Object Enhanced Object Aspects
  • 43. AO Infrastructure Transparent Proxies Enhanced Object Consumer Object Transparent Proxy RealProxy Aspects The transparent proxy is type-compatible with the enhanced object(CLR-provided magic)
  • 44. JIT-Emitted Proxy AO Infrastructure Consumer Object Proxy Enhanced Object Aspects The proxy implements an interface of the enhanced object.
  • 45. JIT-Emitted Subclass AO Infrastructure Consumer Object Proxy Enhanced Object Aspects The proxy extends (inherits from) the enhanced object.
  • 46. Comparing Aspect Frameworks Static vs Dynamic AOP Spring.NET Castle MS Unity/PIAB PostSharp LinFu Build-Time: Very Expressive Robust Model Not InvasiveStatic Run-Time:Less ExpressiveBrittle Model InvasiveDynamic Hybrid
  • 47. Comparing Aspect Frameworks Expressiveness (1/2) What can you do with the framework?
  • 48. Comparing Aspect Frameworks Expressiveness (2/2) How do you apply aspects to code?
  • 49. Comparing Aspect Frameworks Non-Invasiveness Can you use aspects without deep refactoring? Require the use of factory methods
  • 50. Comparing Aspect Frameworks Robustness Can you prevent aspects from being improperly used?
  • 51. Comparing Aspect Frameworks Misc. Other points that matter
  • 52. Comparing Aspect Frameworks My Own Summary Aspects on Service Boundaries: use your favorite application framework. Aspects on Ordinary and GUI Objects: use PostSharp. You can mix PostSharp with your favorite application framework!
  • 55. We have great frameworks! and PostSharp happens to be the best in .NET :).