Fluent interface in c#

1,268 views

Published on

Published in: Technology, Education
0 Comments
0 Likes
Statistics
Notes
  • Be the first to comment

  • Be the first to like this

No Downloads
Views
Total views
1,268
On SlideShare
0
From Embeds
0
Number of Embeds
5
Actions
Shares
0
Downloads
0
Comments
0
Likes
0
Embeds 0
No embeds

No notes for slide
  • DateTime.Now.AddDays(7) DateTime.AddWeeks(1)
  • Example: StringBuilder
  • Example: farm
  • Fluent interface in c#

    1. 1. Domain Specific Languages0 Created specifically to solve problems in a particular domain0 Layer of abstraction on top of an existing domain model0 Can be used by domain experts
    2. 2. DSL Classification DSLsExternal Internal Fluent Interfaces
    3. 3. Fluent Interface0 Term coined by Eric Evens and Martin Fowler http://martinfowler.com/bliki/FluentInterface.html0 Implementation of an object oriented API that aims to provide for more readable code.0 Fluent Interface != Method Chaining
    4. 4. Why should I care?0 Discoverable – easy to use0 Create readable, maintainable code0 Usage directions for users/teammates0 Easy to implement0 No additional libraries needed
    5. 5. Extension Methods0 Quick and easy0 Can be used on 3rd party libraries0 Keep the old API
    6. 6. Extension Methods - Examplevar cheapItmes = Items.Where(item => item.Price < 100) .Select(item => item.Name);public static IEnumerable<TSource> Where(this IEnumerable<TSource> source, Func<TSource, bool>predicate)public static IEnumerable<TResult> Select <TSource, TResult>(this IEnumerable<TSource> source, Func<TSource,TResult> selector)
    7. 7. Method chaining“Make modifier methods return the hostobject, so that multiple modifiers can beinvoked in a single expression”0 Context defined by return value of a called method0 terminated through the return of a void context.
    8. 8. Expression builder“An object, or family of objects, that provide afluent interface over a normal command-queryAPI”var cow = new Animal().Name(“Cow”).Legs(4).Color(Color.Red).Create();
    9. 9. Method chaining in practice0 Use different interfaces to set “stages”0 Use Generics to change return type0 The end of expression problem
    10. 10. Point of entry considerationNUnit:Assert.That (2 + 2, Is.EqualTo(4));Fluent Assertions:(2 + 2).Should().Be(4);
    11. 11. Nested function0 If you need a new instance - use constructors0 Use lambdas for custom operations0 Use expression
    12. 12. Example: Fluent APIs in the wild
    13. 13. Additional resources0 http://martinfowler.com/bliki/FluentInterface.html

    ×