Evolve Your Codepresented byJonathan Birkholz
About MeBlogs : theabsentmindedcoder.comwizardsofsmart.netTwitter : RookieOneGitHub : github.com/RookieOneEmail : rookieone@gmail.com
Virtual Brown BagsWhat : Virtual Brown BagsAn online meeting where the attendees share:Tips and tricksTools, shortcuts, articles, books, patterns, languages, you name itExperiencesThings they’ve learned the hard wayFrustrations or difficultiesFrustrating issues or difficulties they’re facing that somebody else may be able to help them withWhen : Every Thursday @ 12pm – 1pmWhere : http://snipr.com/virtualaltnet Who : Anyone and Everyone
EPS ConsultingCustom Software DevelopmentConsulting / MentoringTrainingWPF.NETCODE MagazineHiring Developers, PM’s
PurposeI would like you to walk away reexamining the way you write your codeAdd some tools to your toolkitShow examples that may inspire you to create your own frameworks
OutlineExtension MethodsLambda ExpressionsExpression TreesFluent Interfaces
Extension methods
What are they?Introduced in .Net 3.5 and Visual Studio 2008Extension 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?LINQExtension method on IEnumerable<T>
Making an extension methodMake a static classWith a static methodFirst parameter is the object to extend (aka ‘this’)123
Using extensionsWithout extensionsWith extensions
SpecUnitTesting extensions
xUnit ExtensionsMore testing extensions
Lambda expressions
What are Lambda Expressions?Introduce in .Net 3.5 and Visual Studio 2008A 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?FuncsFunc<(Of <(T, TResult>)>) DelegateEncapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.ActionsAction<(Of <(T>)>) DelegateEncapsulates a method that takes a single parameter and does not return a value.
FuncsWe can use the defined Func classThen use a lambda to create the Func to use
ActionsWe can use the defined Action classThen 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 VisualizerIn 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 stepsC:\Program Files (x86)\Microsoft Visual Studio 9.0\Samples\1033Unzip CSharpSamples.zip (I extracted mine to C:\CSharpSamples)Go to CSharpSamples\LinqSamples\ExpressionTreeVisualizerOpen ExpressionTreeVisualizer solutionBuild solutionCopy dll from binPaste @ C:\Users\Jonathan Birkholz\Documents\Visual Studio 2008\Visualizers
1 + 1
Visualize 1 + 1
Getting Property Name from Lambda12
Creating Expression by handUsing 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 runtimeOops!
Better NotifyPropertyChangeNow I have compile time checking
Using the Visitor PatternThe 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 VisitorTo implement our own visitor we just inherit from Expression VisitorWe 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 mappingsPOCO Plain Old CLR Object
ProblemIf I wanted POCO domain objects I had to map the EF entities to the appropriate domain objectWhat that left me with wasSo 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 VisitorInstead 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
BeforeETC…
AfterSo now instead of the POCO EmployeeWe have the EF entity Employees
ResultAnd now our repository method can look likeAnd 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 callTerm coined by Eric Evans and Martin Fowler
Method ChainingTypically, 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 ChainingTypical implementation with methods returning void
With Method ChainingInstead of returning void, we return an object to call the next method on
DifferencesMethod chaining isn’t the same as a fluent interfaceA fluent interface is a specific implementation of method chaining to provide a mini-DSLWith strongly typed languages the DSL becomes strongly typed
Square == Fluent InterfaceA square is a specific implementation of a rectangleFluent 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 useWe are seeing more frameworks where fluency is at their coreWe are also seeing frameworks whose purpose is to provide a fluent interface to another frameworkLet’s look at some samples
Structure MapStructureMap is a Dependency Injection / Inversion of Control toolhttp://structuremap.sourceforge.net/Default.htm
Fluent NHibernateFluent, XML-less, compile safe, automated, convention-based mappings for NHibernatehttp://fluentnhibernate.org/
AutomapperAutoMapper uses a fluent configuration API to define an object-object mapping strategyhttp://automapper.codeplex.com/
NBuilderThrough 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 InterfacesTo turn complex operations into readable ones Packaging FunctionalityBuildersConfigurationUtilities
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 ConcernsMethod chaining is difficult to set breakpoints and debugViolates Law of DemeterBreaks Command Query Separation
Difficult to set breakpointsUm… yeah… TRUEYou 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 itselfM's parametersany objects created/instantiated within MO's direct component objects
LoD ExampleBADGOOD
Do fluent interfaces violate LoD?NOAt first glance… yes
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 intentCommand Query SeparationIt states that every method should either be acommand that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer.
CQS Example - SQLQuerySELECTCommandUPDATEDELETEINSERT
Do fluent interfaces violate CQS?YESBut 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 ExampleAdding items to a comboboxThis 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 ExampleGetting selected items from a listboxThis is what we see everywhere…Now it turns to…
Builder PatternBuilder focuses on constructing a complex object step by stepSeparate the construction of a complex object from its representation so that the same construction process can create different representations
Within the object itselfNow our object is polluted with methods used only for fluent construction!This violates the Single Responsibility Principle.
Single Responsibility Principlethe single responsibility principle states that every object should have a single responsibilityA 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 builderNow our fluent builder is in a separate class and doesn’t affect our book class
Value ObjectsA Value Object is an object that describes some characteristic or attribute but carries no concept of identityValue Objects are recommended to be immutableSo we can use a fluent interface builder to construct a value object
Messages are Value Objectshttp://codebetter.com/blogs/gregyoung/archive/2008/04/15/dddd-5-messages-have-fluent-builders.aspxAn unwieldy constructor for a  value objectNow with a fluent builder, we can have an immutable value object without the pain of the gigantic constructor
ConclusionDid you learn anything?See anything new?Be sure to check out the frameworks to see everything we talked about today in actionAlso play with creating your own extension methods, lambdas, expression trees, and fluent interfacesWhen put all together our code can become more readable, easier to learn, and more succinct
Questions?
Git Hub Repositoryhttp://github.com/RookieOne/Evolve-Your-Code Has solution with projects and slide showOffered as is
Third Party FrameworksSpecUnithttp://code.google.com/p/specunit-net/xUnit Extensionshttp://code.google.com/p/xunitbddextensions/Structure Maphttp://structuremap.sourceforge.net/Default.htmAutomapperhttp://automapper.codeplex.com/Fluent Nhibernatehttp://fluentnhibernate.org/NBuilderhttp://nbuilder.org/

Evolve Your Code

  • 1.
    Evolve Your CodepresentedbyJonathan Birkholz
  • 2.
    About MeBlogs :theabsentmindedcoder.comwizardsofsmart.netTwitter : RookieOneGitHub : github.com/RookieOneEmail : rookieone@gmail.com
  • 3.
    Virtual Brown BagsWhat: Virtual Brown BagsAn online meeting where the attendees share:Tips and tricksTools, shortcuts, articles, books, patterns, languages, you name itExperiencesThings they’ve learned the hard wayFrustrations or difficultiesFrustrating issues or difficulties they’re facing that somebody else may be able to help them withWhen : Every Thursday @ 12pm – 1pmWhere : http://snipr.com/virtualaltnet Who : Anyone and Everyone
  • 4.
    EPS ConsultingCustom SoftwareDevelopmentConsulting / MentoringTrainingWPF.NETCODE MagazineHiring Developers, PM’s
  • 5.
    PurposeI would likeyou to walk away reexamining the way you write your codeAdd some tools to your toolkitShow examples that may inspire you to create your own frameworks
  • 6.
  • 7.
  • 8.
    What are they?Introducedin .Net 3.5 and Visual Studio 2008Extension 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 Iseen them before?LINQExtension method on IEnumerable<T>
  • 10.
    Making an extensionmethodMake a static classWith a static methodFirst parameter is the object to extend (aka ‘this’)123
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
    What are LambdaExpressions?Introduce in .Net 3.5 and Visual Studio 2008A 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 Iseen them before?Linq uses lambda expressions Is the same as…
  • 17.
  • 18.
    How can Iuse them?FuncsFunc<(Of <(T, TResult>)>) DelegateEncapsulates a method that has one parameter and returns a value of the type specified by the TResult parameter.ActionsAction<(Of <(T>)>) DelegateEncapsulates a method that takes a single parameter and does not return a value.
  • 19.
    FuncsWe can usethe defined Func classThen use a lambda to create the Func to use
  • 20.
    ActionsWe can usethe defined Action classThen use a lambda to create the action to use
  • 21.
  • 22.
    What are they?Expressiontrees 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.
  • 23.
  • 24.
  • 25.
    Expression Tree VisualizerInorder 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 stepsC:\Program Files (x86)\Microsoft Visual Studio 9.0\Samples\1033Unzip CSharpSamples.zip (I extracted mine to C:\CSharpSamples)Go to CSharpSamples\LinqSamples\ExpressionTreeVisualizerOpen ExpressionTreeVisualizer solutionBuild solutionCopy dll from binPaste @ C:\Users\Jonathan Birkholz\Documents\Visual Studio 2008\Visualizers
  • 26.
  • 27.
  • 28.
  • 29.
    Creating Expression byhandUsing a Lambda
  • 30.
  • 31.
    Cool but whywould 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 runtimeOops!
  • 32.
    Better NotifyPropertyChangeNow Ihave compile time checking
  • 33.
    Using the VisitorPatternThe 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 VisitorTo implementour own visitor we just inherit from Expression VisitorWe then can override the virtual methods that are called when visiting specific expression elements in the expression tree
  • 35.
  • 36.
  • 37.
    Usage?I created aPOCO Entity Framework prototype using Expression Visitor and mappingsPOCO Plain Old CLR Object
  • 38.
    ProblemIf I wantedPOCO domain objects I had to map the EF entities to the appropriate domain objectWhat that left me with wasSo 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 VisitorInsteadof 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
  • 40.
  • 41.
    AfterSo now insteadof the POCO EmployeeWe have the EF entity Employees
  • 42.
    ResultAnd now ourrepository method can look likeAnd we only pull the entities we need because EF can send the correct SQL to the database
  • 43.
  • 44.
    What are they?Afluent 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 callTerm coined by Eric Evans and Martin Fowler
  • 45.
    Method ChainingTypically, methodchaining 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 ChainingTypicalimplementation with methods returning void
  • 47.
    With Method ChainingInsteadof returning void, we return an object to call the next method on
  • 48.
    DifferencesMethod chaining isn’tthe same as a fluent interfaceA fluent interface is a specific implementation of method chaining to provide a mini-DSLWith strongly typed languages the DSL becomes strongly typed
  • 49.
    Square == FluentInterfaceA square is a specific implementation of a rectangleFluent interfaces use method chaining but not all method chains are a fluent interface
  • 50.
    All the rage…Manyframeworks now offer fluent interfaces for configuration and ease of useWe are seeing more frameworks where fluency is at their coreWe are also seeing frameworks whose purpose is to provide a fluent interface to another frameworkLet’s look at some samples
  • 51.
    Structure MapStructureMap isa Dependency Injection / Inversion of Control toolhttp://structuremap.sourceforge.net/Default.htm
  • 52.
    Fluent NHibernateFluent, XML-less,compile safe, automated, convention-based mappings for NHibernatehttp://fluentnhibernate.org/
  • 53.
    AutomapperAutoMapper uses afluent configuration API to define an object-object mapping strategyhttp://automapper.codeplex.com/
  • 54.
    NBuilderThrough 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 useFluent InterfacesTo turn complex operations into readable ones Packaging FunctionalityBuildersConfigurationUtilities
  • 56.
    Is it anAPI 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 ConcernsMethod chainingis difficult to set breakpoints and debugViolates Law of DemeterBreaks Command Query Separation
  • 58.
    Difficult to setbreakpointsUm… yeah… TRUEYou 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“Onlytalk 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 itselfM's parametersany objects created/instantiated within MO's direct component objects
  • 60.
  • 61.
    Do fluent interfacesviolate LoD?NOAt first glance… yes
  • 62.
    But we needto 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 saythe interaction between objects should be based around behavior and not on state
  • 64.
    If we examinethe intent of the Law of Demeter, then NO it doesn’t violate the intentCommand Query SeparationIt states that every method should either be acommand that performs an action, or a query that returns data to the caller, but not both. In other words, asking a question should not change the answer.
  • 65.
    CQS Example -SQLQuerySELECTCommandUPDATEDELETEINSERT
  • 66.
    Do fluent interfacesviolate CQS?YESBut 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 offluent interfaces
  • 68.
    Add ExampleAdding itemsto a comboboxThis 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 ExampleGetting selecteditems from a listboxThis is what we see everywhere…Now it turns to…
  • 70.
    Builder PatternBuilder focuseson constructing a complex object step by stepSeparate the construction of a complex object from its representation so that the same construction process can create different representations
  • 71.
    Within the objectitselfNow our object is polluted with methods used only for fluent construction!This violates the Single Responsibility Principle.
  • 72.
    Single Responsibility Principlethesingle responsibility principle states that every object should have a single responsibilityA 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 builderNowour fluent builder is in a separate class and doesn’t affect our book class
  • 74.
    Value ObjectsA ValueObject is an object that describes some characteristic or attribute but carries no concept of identityValue Objects are recommended to be immutableSo we can use a fluent interface builder to construct a value object
  • 75.
    Messages are ValueObjectshttp://codebetter.com/blogs/gregyoung/archive/2008/04/15/dddd-5-messages-have-fluent-builders.aspxAn unwieldy constructor for a value objectNow with a fluent builder, we can have an immutable value object without the pain of the gigantic constructor
  • 76.
    ConclusionDid you learnanything?See anything new?Be sure to check out the frameworks to see everything we talked about today in actionAlso play with creating your own extension methods, lambdas, expression trees, and fluent interfacesWhen put all together our code can become more readable, easier to learn, and more succinct
  • 77.
  • 78.
    Git Hub Repositoryhttp://github.com/RookieOne/Evolve-Your-CodeHas solution with projects and slide showOffered as is
  • 79.
    Third Party FrameworksSpecUnithttp://code.google.com/p/specunit-net/xUnitExtensionshttp://code.google.com/p/xunitbddextensions/Structure Maphttp://structuremap.sourceforge.net/Default.htmAutomapperhttp://automapper.codeplex.com/Fluent Nhibernatehttp://fluentnhibernate.org/NBuilderhttp://nbuilder.org/
  • 80.
  • 81.