SlideShare ist ein Scribd-Unternehmen logo
1 von 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

Weitere ähnliche Inhalte

Andere mochten auch

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
 

Andere mochten auch (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
 

Ähnlich wie Introduction to Aspect-Oriented Programming with PostSharp

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
 

Ähnlich wie Introduction to Aspect-Oriented Programming with PostSharp (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
 

Mehr von 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
 

Mehr von 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
 

Kürzlich hochgeladen

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 

Kürzlich hochgeladen (20)

Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 
Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 

Introduction to Aspect-Oriented Programming with PostSharp

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