SlideShare a Scribd company logo
1 of 56
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 ProgrammingYan Cui
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented ProgrammingAnumod Kumar
 
Apache Solr lessons learned
Apache Solr lessons learnedApache Solr lessons learned
Apache Solr lessons learnedJeroen Rosenberg
 
Aspect Oriented Programming
Aspect Oriented ProgrammingAspect Oriented Programming
Aspect Oriented ProgrammingRodger Oates
 
Spring aop concepts
Spring aop conceptsSpring aop concepts
Spring aop conceptsRushiBShah
 
Aspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPAspect-Oriented Programming for PHP
Aspect-Oriented Programming for PHPWilliam Candillon
 
Aspect Oriented Software Development
Aspect Oriented Software DevelopmentAspect Oriented Software Development
Aspect Oriented Software DevelopmentJignesh Patel
 

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 Managementpritamkumar
 
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 JavascriptWalid 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 learnedMarcinStachniuk
 
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.0PhilWinstanley
 
HashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureHashiCorp Vault Plugin Infrastructure
HashiCorp Vault Plugin InfrastructureNicolas Corrarello
 
Introduction to trader bots with Python
Introduction to trader bots with PythonIntroduction to trader bots with Python
Introduction to trader bots with Pythonroskakori
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptdominion
 
C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴C#을 이용한 task 병렬화와 비동기 패턴
C#을 이용한 task 병렬화와 비동기 패턴명신 김
 
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) Datagreenwop
 
Improving Correctness with Types
Improving Correctness with TypesImproving Correctness with Types
Improving Correctness with TypesIain 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 ProgrammerSrikanth 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 ModelsPostSharp 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 DesignPostSharp 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 AutomationPostSharp 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 PerformancePostSharp 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 ProgrammingPostSharp 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

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FMESafe Software
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxRemote DBA Services
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamUiPathCommunity
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesrafiqahmad00786416
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Angeliki Cooney
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...apidays
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdfSandro Moreira
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusZilliz
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...apidays
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWERMadyBayot
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxRustici Software
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...Zilliz
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
 

Recently uploaded (20)

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 

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 :).