SlideShare ist ein Scribd-Unternehmen logo
1 von 79
Evolve Your Code presented by Jonathan Birkholz
About Me Blogs :  theabsentmindedcoder.com wizardsofsmart.net Twitter : RookieOne GitHub : github.com/RookieOne Email : rookieone@gmail.com
Virtual Brown Bags What : Virtual Brown Bags An online meeting where the attendees share: Tips and tricks Tools, shortcuts, articles, books, patterns, languages, you name it Experiences Things they’ve learned the hard way Frustrations or difficulties Frustrating issues or difficulties they’re facing that somebody else may be able to help them with When : Every Thursday @ 12pm – 1pm Where : http://snipr.com/virtualaltnet  Who : Anyone and Everyone
EPS Consulting Custom Software Development Consulting / Mentoring Training WPF .NET CODE Magazine Hiring Developers, PM’s
Purpose I would like you to walk away reexamining the way you write your code Add some tools to your toolkit Show examples that may inspire you to create your own frameworks
Outline Extension Methods Lambda Expressions Expression Trees Fluent Interfaces
Extension methods
What are they? Introduced in .Net 3.5 and Visual Studio 2008 Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
Where have I seen them before? LINQ Extension method on IEnumerable<T>
Making an extension method Make a static class With a static method First parameter is the object to extend (aka ‘this’) 1 2 3
Using extensions Without extensions With extensions
SpecUnit Testing extensions
xUnit Extensions More testing extensions
Lambda expressions
What are Lambda Expressions? Introduce in .Net 3.5 and Visual Studio 2008 A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types
Where have I seen them before? Linq uses lambda expressions  Is the same as…
As event handlers as well
How can I use them? Funcs Func<(Of <(T, TResult>)>) Delegate Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter. Actions Action<(Of <(T>)>) Delegate Encapsulates a method that takes a single parameter and does not return a value.
Funcs We can use the defined Func class Then use a lambda to create the Func to use
Actions We can use the defined Action class Then use a lambda to create the action to use
Expression Trees
What are they? Expression trees represent language-level code in the form of data. The data is stored in a tree-shaped structure. Each node in the expression tree represents an expression, for example a method call or a binary operation such as x < y.
Say what?!
Ok… how about this…
Expression Tree Visualizer In order to get this visualizer you need to go to the samples folder where you installed VS and open the visualizer project and build it then copy it to the visualizer folder in Documents and Settings for your user. My steps C:rogram Files (x86)icrosoft Visual Studio 9.0amples033 Unzip CSharpSamples.zip (I extracted mine to C:SharpSamples) Go to CSharpSamplesinqSamplesxpressionTreeVisualizer Open ExpressionTreeVisualizer solution Build solution Copy dll from bin Paste @ C:sersonathan Birkholzocumentsisual Studio 2008isualizers
1 + 1
Visualize 1 + 1
Getting Property Name from Lambda 1 2
Creating Expression by hand Using a Lambda
Visualize Property Expression
Cool but why would I care? Notify Property Changed how I hate you… String is not strongly typed, you can easily mistype the property name and wouldn’t know until runtime Oops!
Better NotifyPropertyChange Now I have compile time checking
Using the Visitor Pattern The visitor pattern’s primary purpose is to abstract functionality that can be applied to an aggregate hierarchy of “element” objects. Microsoft provides an Expression Tree Visitor @MSDN : http://msdn.microsoft.com/en-us/library/bb882521.aspx
Expression Visitor To implement our own visitor we just inherit from Expression Visitor We then can override the virtual methods that are called when visiting specific expression elements in the expression tree
Console Visitor
Just visiting
Usage? I created a POCO Entity Framework prototype using Expression Visitor and mappings POCO  Plain  Old  CLR  Object
Problem If I wanted POCO domain objects I had to map the EF entities to the appropriate domain object What that left me with was So I had to pull back every Employee from the database so I could map and then check the LastName property on my domain object
Using Expression Visitor Instead of that horrible solution, lets take the expression and use the visitor to replace all the references to our domain object with references to the EF entity
Before ETC…
After So now instead of the POCO Employee We have the EF entity Employees
Result And now our repository method can look like And we only pull the entities we need	 because EF can send the correct SQL to the database
Fluent interfaces
What are they? A fluent interface is  a way of implementing an object oriented API in a way that aims to provide for more readable code. normally implemented by using method chaining to relay the instruction context of a subsequent call Term coined by Eric Evans and Martin Fowler
Method Chaining Typically, method chaining simply consists of many methods on a class, each of which return the current object itself. It can return a different object, but the more typical method chaining scenarios return the current object
Without Method Chaining Typical implementation with methods returning void
With Method Chaining Instead of returning void, we return an object to call the next method on
Differences Method chaining isn’t the same as a fluent interface A fluent interface is a specific implementation of method chaining to provide a mini-DSL With strongly typed languages the DSL becomes strongly typed
Square == Fluent Interface A square is a specific implementation of a rectangle Fluent interfaces use method chaining but not all method chains are a fluent interface
All the rage… Many frameworks now offer fluent interfaces for configuration and ease of use We are seeing more frameworks where fluency is at their core We are also seeing frameworks whose purpose is to provide a fluent interface to another framework Let’s look at some samples
Structure Map StructureMap is a Dependency Injection / Inversion of Control tool http://structuremap.sourceforge.net/Default.htm
Fluent NHibernate Fluent, XML-less, compile safe, automated, convention-based mappings for NHibernate http://fluentnhibernate.org/
Automapper AutoMapper uses a fluent configuration API to define an object-object mapping strategy http://automapper.codeplex.com/
NBuilder Through a fluent, extensible interface, NBuilder allows you to rapidly create test data, automatically assigning values to properties and public fields that are of type of the built in .NET data types (e.g. ints and strings). http://nbuilder.org/
When to use Fluent Interfaces To turn complex operations into readable ones  Packaging Functionality Builders Configuration Utilities
Is it an API or a DSL? Whether fluent interface is a form of DSL or not, it's obviously a form of fluent interface. - Scott Bellware
Common Concerns Method chaining is difficult to set breakpoints and debug Violates Law of Demeter Breaks Command Query Separation
Difficult to set breakpoints Um… yeah… TRUE You can put break points in the methods or just step debug through chain but in the end, it is more difficult to debug
Law of Demeter “Only talk to your immediate friends.” the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects: O itself M's parameters any objects created/instantiated within M O's direct component objects
LoD Example BAD GOOD
Do fluent interfaces violate LoD? NO ,[object Object]
But we need to examine the intent of the Law of Demeter which is to limit the dependency of objects on the structure of other objects
One could say the interaction between objects should be based around behavior and not on state
If we examine the intent of the Law of Demeter, then NO it doesn’t violate the intent,[object Object]
CQS Example - SQL Query SELECT Command UPDATE DELETE INSERT
Do fluent interfaces violate CQS? YES But we purposefully violate the principle in order to accomplish a readable DSL  The violation of CQS is a good reason why fluent interfaces tend to work better in builders, configurations, and utilities and not in domain objects (IMHO)
Simple examples of fluent interfaces
Add Example Adding items to a combobox This is what we see everywhere… Now it turns to… And we now can manage how items are adding to comboboxes for the entire solution
Selected Example Getting selected items from a listbox This is what we see everywhere… Now it turns to…
Builder Pattern Builder focuses on constructing a complex object step by step Separate the construction of a complex object from its representation so that the same construction process can create different representations
Within the object itself Now our object is polluted with methods used only for fluent construction! This violates the  Single Responsibility Principle.
Single Responsibility Principle the single responsibility principle states that every object should have a single responsibility A class should have one, and only one, reason to change. FluentBook can change if we need to change the functionality of the FluentBook AND if we want to change how we construct the book fluently
Using a builder Now our fluent builder is in a separate class and doesn’t affect our book class
Value Objects A Value Object is an object that describes some characteristic or attribute but carries no concept of identity Value Objects are recommended to be immutable So we can use a fluent interface builder to construct a value object
Messages are Value Objects http://codebetter.com/blogs/gregyoung/archive/2008/04/15/dddd-5-messages-have-fluent-builders.aspx An unwieldy constructor for a  value object Now with a fluent builder, we can have an immutable value object without the pain of the gigantic constructor
Conclusion Did you learn anything? See anything new? Be sure to check out the frameworks to see everything we talked about today in action Also play with creating your own extension methods, lambdas, expression trees, and fluent interfaces When put all together our code can become more readable, easier to learn, and more succinct
Questions ?
Git Hub Repository http://github.com/RookieOne/Evolve-Your-Code  Has solution with projects and slide show Offered as is
Third Party Frameworks SpecUnit http://code.google.com/p/specunit-net/ xUnit Extensions http://code.google.com/p/xunitbddextensions/ Structure Map http://structuremap.sourceforge.net/Default.htm Automapper http://automapper.codeplex.com/ Fluent Nhibernate http://fluentnhibernate.org/ NBuilder http://nbuilder.org/

Weitere ähnliche Inhalte

Was ist angesagt?

Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentalsmegharajk
 
Coders club java tutorial
Coders club java tutorialCoders club java tutorial
Coders club java tutorialShivaum Kumar
 
Conventional and Reasonable
Conventional and ReasonableConventional and Reasonable
Conventional and ReasonableKevlin Henney
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design patternMindfire Solutions
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringEyob Lube
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script PatternsAllan Huang
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The EnterpriseDaniel Egan
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Alexander Pashynskiy
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in RefactoringChamnap Chhorn
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#Hawkman Academy
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesEdorian
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerIgor Crvenov
 

Was ist angesagt? (20)

Code Smell
Code SmellCode Smell
Code Smell
 
Abstract
AbstractAbstract
Abstract
 
Java se 8 fundamentals
Java se 8 fundamentalsJava se 8 fundamentals
Java se 8 fundamentals
 
Coders club java tutorial
Coders club java tutorialCoders club java tutorial
Coders club java tutorial
 
Conventional and Reasonable
Conventional and ReasonableConventional and Reasonable
Conventional and Reasonable
 
Design pattern
Design patternDesign pattern
Design pattern
 
Let us understand design pattern
Let us understand design patternLet us understand design pattern
Let us understand design pattern
 
C# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoringC# coding standards, good programming principles & refactoring
C# coding standards, good programming principles & refactoring
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Java Script Patterns
Java Script PatternsJava Script Patterns
Java Script Patterns
 
Arrays in Objective-C
Arrays in Objective-CArrays in Objective-C
Arrays in Objective-C
 
Linq To The Enterprise
Linq To The EnterpriseLinq To The Enterprise
Linq To The Enterprise
 
Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"Java day2016 "Reinventing design patterns with java 8"
Java day2016 "Reinventing design patterns with java 8"
 
Principles in Refactoring
Principles in RefactoringPrinciples in Refactoring
Principles in Refactoring
 
C# concepts
C# conceptsC# concepts
C# concepts
 
C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#C# 101: Intro to Programming with C#
C# 101: Intro to Programming with C#
 
API Design
API DesignAPI Design
API Design
 
Sda 8
Sda   8Sda   8
Sda 8
 
Stop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principlesStop wasting-time-by-applying-clean-code-principles
Stop wasting-time-by-applying-clean-code-principles
 
Refactoring Tips by Martin Fowler
Refactoring Tips by Martin FowlerRefactoring Tips by Martin Fowler
Refactoring Tips by Martin Fowler
 

Andere mochten auch (7)

Toscana
ToscanaToscana
Toscana
 
Around The World
Around The WorldAround The World
Around The World
 
Saint Petersburg
Saint PetersburgSaint Petersburg
Saint Petersburg
 
Parkokzenvel
ParkokzenvelParkokzenvel
Parkokzenvel
 
Scandinavia
ScandinaviaScandinavia
Scandinavia
 
Vancouver Photo
Vancouver PhotoVancouver Photo
Vancouver Photo
 
117908 elfee
117908 elfee117908 elfee
117908 elfee
 

Ähnlich wie Evolve Your Code

Importance Of Being Driven
Importance Of Being DrivenImportance Of Being Driven
Importance Of Being DrivenAntonio Terreno
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural PatternsSameh Deabes
 
Framework Design Guidelines
Framework Design GuidelinesFramework Design Guidelines
Framework Design GuidelinesMohamed Meligy
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Groupbrada
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9google
 
Developing Actors in Azure with .net
Developing Actors in Azure with .netDeveloping Actors in Azure with .net
Developing Actors in Azure with .netMarco Parenzan
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Bill Buchan
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The LambdaTogakangaroo
 
How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructuremichael.labriola
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questionsnicolbiden
 
Design Patterns
Design PatternsDesign Patterns
Design Patternsimedo.de
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8icarter09
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxdanhaley45372
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsLalit Kale
 

Ähnlich wie Evolve Your Code (20)

Advance oops concepts
Advance oops conceptsAdvance oops concepts
Advance oops concepts
 
Importance Of Being Driven
Importance Of Being DrivenImportance Of Being Driven
Importance Of Being Driven
 
GoF Design patterns I: Introduction + Structural Patterns
GoF Design patterns I:   Introduction + Structural PatternsGoF Design patterns I:   Introduction + Structural Patterns
GoF Design patterns I: Introduction + Structural Patterns
 
Framework Design Guidelines
Framework Design GuidelinesFramework Design Guidelines
Framework Design Guidelines
 
C# interview
C# interviewC# interview
C# interview
 
Framework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users GroupFramework Design Guidelines For Brussels Users Group
Framework Design Guidelines For Brussels Users Group
 
Linq 1224887336792847 9
Linq 1224887336792847 9Linq 1224887336792847 9
Linq 1224887336792847 9
 
Entity Framework 4
Entity Framework 4Entity Framework 4
Entity Framework 4
 
Developing Actors in Azure with .net
Developing Actors in Azure with .netDeveloping Actors in Azure with .net
Developing Actors in Azure with .net
 
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
Lotusphere 2007 AD507 Leveraging the Power of Object Oriented Programming in ...
 
Can't Dance The Lambda
Can't Dance The LambdaCan't Dance The Lambda
Can't Dance The Lambda
 
How To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex InfrastructureHow To Navigate And Extend The Flex Infrastructure
How To Navigate And Extend The Flex Infrastructure
 
Graphql
GraphqlGraphql
Graphql
 
Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02Go f designpatterns 130116024923-phpapp02
Go f designpatterns 130116024923-phpapp02
 
C# interview-questions
C# interview-questionsC# interview-questions
C# interview-questions
 
Bp301
Bp301Bp301
Bp301
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Lambda Expressions in Java 8
Lambda Expressions in Java 8Lambda Expressions in Java 8
Lambda Expressions in Java 8
 
Patterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docxPatterns (contd)Software Development ProcessDesign patte.docx
Patterns (contd)Software Development ProcessDesign patte.docx
 
Jump Start To Ooad And Design Patterns
Jump Start To Ooad And Design PatternsJump Start To Ooad And Design Patterns
Jump Start To Ooad And Design Patterns
 

Kürzlich hochgeladen

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxBkGupta21
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
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
 
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
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfMounikaPolabathina
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxLoriGlavin3
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 

Kürzlich hochgeladen (20)

unit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptxunit 4 immunoblotting technique complete.pptx
unit 4 immunoblotting technique complete.pptx
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
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
 
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?
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
What is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdfWhat is DBT - The Ultimate Data Build Tool.pdf
What is DBT - The Ultimate Data Build Tool.pdf
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
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
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptxThe Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
The Role of FIDO in a Cyber Secure Netherlands: FIDO Paris Seminar.pptx
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 

Evolve Your Code

  • 1. Evolve Your Code presented by Jonathan Birkholz
  • 2. About Me Blogs : theabsentmindedcoder.com wizardsofsmart.net Twitter : RookieOne GitHub : github.com/RookieOne Email : rookieone@gmail.com
  • 3. Virtual Brown Bags What : Virtual Brown Bags An online meeting where the attendees share: Tips and tricks Tools, shortcuts, articles, books, patterns, languages, you name it Experiences Things they’ve learned the hard way Frustrations or difficulties Frustrating issues or difficulties they’re facing that somebody else may be able to help them with When : Every Thursday @ 12pm – 1pm Where : http://snipr.com/virtualaltnet Who : Anyone and Everyone
  • 4. EPS Consulting Custom Software Development Consulting / Mentoring Training WPF .NET CODE Magazine Hiring Developers, PM’s
  • 5. Purpose I would like you to walk away reexamining the way you write your code Add some tools to your toolkit Show examples that may inspire you to create your own frameworks
  • 6. Outline Extension Methods Lambda Expressions Expression Trees Fluent Interfaces
  • 8. What are they? Introduced in .Net 3.5 and Visual Studio 2008 Extension methods enable you to "add" methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
  • 9. Where have I seen them before? LINQ Extension method on IEnumerable<T>
  • 10. Making an extension method Make a static class With a static method First parameter is the object to extend (aka ‘this’) 1 2 3
  • 11. Using extensions Without extensions With extensions
  • 13. xUnit Extensions More testing extensions
  • 15. What are Lambda Expressions? Introduce in .Net 3.5 and Visual Studio 2008 A lambda expression is an anonymous function that can contain expressions and statements, and can be used to create delegates or expression tree types
  • 16. Where have I seen them before? Linq uses lambda expressions Is the same as…
  • 17. As event handlers as well
  • 18. How can I use them? Funcs Func<(Of <(T, TResult>)>) Delegate Encapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter. Actions Action<(Of <(T>)>) Delegate Encapsulates a method that takes a single parameter and does not return a value.
  • 19. Funcs We can use the defined Func class Then use a lambda to create the Func to use
  • 20. Actions We can use the defined Action class Then use a lambda to create the action to use
  • 22. What are they? Expression trees represent language-level code in the form of data. The data is stored in a tree-shaped structure. Each node in the expression tree represents an expression, for example a method call or a binary operation such as x < y.
  • 24. Ok… how about this…
  • 25. Expression Tree Visualizer In order to get this visualizer you need to go to the samples folder where you installed VS and open the visualizer project and build it then copy it to the visualizer folder in Documents and Settings for your user. My steps C:rogram Files (x86)icrosoft Visual Studio 9.0amples033 Unzip CSharpSamples.zip (I extracted mine to C:SharpSamples) Go to CSharpSamplesinqSamplesxpressionTreeVisualizer Open ExpressionTreeVisualizer solution Build solution Copy dll from bin Paste @ C:sersonathan Birkholzocumentsisual Studio 2008isualizers
  • 26. 1 + 1
  • 28. Getting Property Name from Lambda 1 2
  • 29. Creating Expression by hand Using a Lambda
  • 31. Cool but why would I care? Notify Property Changed how I hate you… String is not strongly typed, you can easily mistype the property name and wouldn’t know until runtime Oops!
  • 32. Better NotifyPropertyChange Now I have compile time checking
  • 33. Using the Visitor Pattern The visitor pattern’s primary purpose is to abstract functionality that can be applied to an aggregate hierarchy of “element” objects. Microsoft provides an Expression Tree Visitor @MSDN : http://msdn.microsoft.com/en-us/library/bb882521.aspx
  • 34. Expression Visitor To implement our own visitor we just inherit from Expression Visitor We then can override the virtual methods that are called when visiting specific expression elements in the expression tree
  • 37. Usage? I created a POCO Entity Framework prototype using Expression Visitor and mappings POCO Plain Old CLR Object
  • 38. Problem If I wanted POCO domain objects I had to map the EF entities to the appropriate domain object What that left me with was So I had to pull back every Employee from the database so I could map and then check the LastName property on my domain object
  • 39. Using Expression Visitor Instead of that horrible solution, lets take the expression and use the visitor to replace all the references to our domain object with references to the EF entity
  • 41. After So now instead of the POCO Employee We have the EF entity Employees
  • 42. Result And now our repository method can look like And we only pull the entities we need because EF can send the correct SQL to the database
  • 44. What are they? A fluent interface is a way of implementing an object oriented API in a way that aims to provide for more readable code. normally implemented by using method chaining to relay the instruction context of a subsequent call Term coined by Eric Evans and Martin Fowler
  • 45. Method Chaining Typically, method chaining simply consists of many methods on a class, each of which return the current object itself. It can return a different object, but the more typical method chaining scenarios return the current object
  • 46. Without Method Chaining Typical implementation with methods returning void
  • 47. With Method Chaining Instead of returning void, we return an object to call the next method on
  • 48. Differences Method chaining isn’t the same as a fluent interface A fluent interface is a specific implementation of method chaining to provide a mini-DSL With strongly typed languages the DSL becomes strongly typed
  • 49. Square == Fluent Interface A square is a specific implementation of a rectangle Fluent interfaces use method chaining but not all method chains are a fluent interface
  • 50. All the rage… Many frameworks now offer fluent interfaces for configuration and ease of use We are seeing more frameworks where fluency is at their core We are also seeing frameworks whose purpose is to provide a fluent interface to another framework Let’s look at some samples
  • 51. Structure Map StructureMap is a Dependency Injection / Inversion of Control tool http://structuremap.sourceforge.net/Default.htm
  • 52. Fluent NHibernate Fluent, XML-less, compile safe, automated, convention-based mappings for NHibernate http://fluentnhibernate.org/
  • 53. Automapper AutoMapper uses a fluent configuration API to define an object-object mapping strategy http://automapper.codeplex.com/
  • 54. NBuilder Through a fluent, extensible interface, NBuilder allows you to rapidly create test data, automatically assigning values to properties and public fields that are of type of the built in .NET data types (e.g. ints and strings). http://nbuilder.org/
  • 55. When to use Fluent Interfaces To turn complex operations into readable ones Packaging Functionality Builders Configuration Utilities
  • 56. Is it an API or a DSL? Whether fluent interface is a form of DSL or not, it's obviously a form of fluent interface. - Scott Bellware
  • 57. Common Concerns Method chaining is difficult to set breakpoints and debug Violates Law of Demeter Breaks Command Query Separation
  • 58. Difficult to set breakpoints Um… yeah… TRUE You can put break points in the methods or just step debug through chain but in the end, it is more difficult to debug
  • 59. Law of Demeter “Only talk to your immediate friends.” the Law of Demeter for functions requires that a method M of an object O may only invoke the methods of the following kinds of objects: O itself M's parameters any objects created/instantiated within M O's direct component objects
  • 61.
  • 62. But we need to examine the intent of the Law of Demeter which is to limit the dependency of objects on the structure of other objects
  • 63. One could say the interaction between objects should be based around behavior and not on state
  • 64.
  • 65. CQS Example - SQL Query SELECT Command UPDATE DELETE INSERT
  • 66. Do fluent interfaces violate CQS? YES But we purposefully violate the principle in order to accomplish a readable DSL The violation of CQS is a good reason why fluent interfaces tend to work better in builders, configurations, and utilities and not in domain objects (IMHO)
  • 67. Simple examples of fluent interfaces
  • 68. Add Example Adding items to a combobox This is what we see everywhere… Now it turns to… And we now can manage how items are adding to comboboxes for the entire solution
  • 69. Selected Example Getting selected items from a listbox This is what we see everywhere… Now it turns to…
  • 70. Builder Pattern Builder focuses on constructing a complex object step by step Separate the construction of a complex object from its representation so that the same construction process can create different representations
  • 71. Within the object itself Now our object is polluted with methods used only for fluent construction! This violates the Single Responsibility Principle.
  • 72. Single Responsibility Principle the single responsibility principle states that every object should have a single responsibility A class should have one, and only one, reason to change. FluentBook can change if we need to change the functionality of the FluentBook AND if we want to change how we construct the book fluently
  • 73. Using a builder Now our fluent builder is in a separate class and doesn’t affect our book class
  • 74. Value Objects A Value Object is an object that describes some characteristic or attribute but carries no concept of identity Value Objects are recommended to be immutable So we can use a fluent interface builder to construct a value object
  • 75. Messages are Value Objects http://codebetter.com/blogs/gregyoung/archive/2008/04/15/dddd-5-messages-have-fluent-builders.aspx An unwieldy constructor for a value object Now with a fluent builder, we can have an immutable value object without the pain of the gigantic constructor
  • 76. Conclusion Did you learn anything? See anything new? Be sure to check out the frameworks to see everything we talked about today in action Also play with creating your own extension methods, lambdas, expression trees, and fluent interfaces When put all together our code can become more readable, easier to learn, and more succinct
  • 78. Git Hub Repository http://github.com/RookieOne/Evolve-Your-Code Has solution with projects and slide show Offered as is
  • 79. Third Party Frameworks SpecUnit http://code.google.com/p/specunit-net/ xUnit Extensions http://code.google.com/p/xunitbddextensions/ Structure Map http://structuremap.sourceforge.net/Default.htm Automapper http://automapper.codeplex.com/ Fluent Nhibernate http://fluentnhibernate.org/ NBuilder http://nbuilder.org/
  • 80. Resources MSDN Wikipedia Martin Fowler http://www.martinfowler.com/ J.P. Hamilton http://www.jphamilton.net/post/MVVM-with-Type-Safe-INotifyPropertyChanged.aspx Rob Conery http://blog.wekeroad.com/blog/working-with-linq-s-expression-trees-visually/
  • 81. Resources II Barnett http://weblogs.asp.net/gbarnett/archive/2007/09/15/expression-tree-visualizer.aspx Greg Young http://codebetter.com/blogs/gregyoung/archive/2007/12/05/a-use-for-extension-methods.aspx http://sourcemaking.com/design_patterns/visitor