Are there any Fluent interfaces?

I read about Fluent APIs, where the code can be made to read like English, but I can not find any examples of them, since I would like to know if they are a reasonable way to make it easy to use the interface for the system by programmers who do not use the full working day. Does anyone have any examples of a free interface?

+4
source share
5 answers

I am a jOOQ developer who comes with a smooth API for dynamically building specification SQL queries. Example:

create.select(FIRST_NAME, LAST_NAME, count()) .from(AUTHORS) .join(BOOKS) .using(AUTHOR_ID) .groupBy(FIRST_NAME, LAST_NAME) .orderBy(LAST_NAME); 

The main SQL query is “hidden” behind several interfaces that model each “step” involved in creating the query. This means that .select(Field...) returns an interface that provides access to the .from(Table) method, which, in turn, returns an interface that provides access to the .join(Table) method, etc.

SQL is actually a DSL that is external to Java. With jOOQ (or any other free API), SQL can be "internalized" in Java to a certain extent. Unlike external DSL, some SQL-specific constructors are difficult to map to internal DSL in Java. An example of this is smoothing.

See here for more documentation:

http://www.jooq.org/manual/DSL/

Update

At the same time, I came across another very interesting free API used to create RTF files with Java. Code example:

 rtf().section( p( "first paragraph" ), p( tab(), " second par ", bold( "with something in bold" ), text( " and " ), italic( underline( "italic underline" ) ) ) ).out( out ); 

More details here:

http://code.google.com/p/jrtf/

+2
source

A couple of examples below in C #. Used by non-programmers? Well, decide for yourself, I would probably say no - they are for encoders, and you need to know the syntax. But then this is C #, there are better examples in Ruby and other languages ​​with much more readable syntax in English.

You might also want to see external DSLs (domain specific languages). (Fluent APIs are considered internal DSLs).

NUnit:

 Assert.That(result, Is.EqualTo(10)); 

Ninject:

 Bind<IDataAccess>() .To<Db4oDataAccess>() .WithConstructorArgument("fileName", "dbFile.db"); 

Rhino Mocks:

 repository.Expect(x => x.LoadUserList()).Return(users); 

Here are some Ruby from RSpec:

 @account.balance.should eql(Money.new(0, :dollars)) 

However, keep in mind that these examples are aimed at programmers, you can get much more human-readable code if non-programmers are the target audience, especially with Ruby, etc.

+5
source

Here is a pretty good example:

http://www.google.com/codesearch/p?hl=en#CICsffyVkoc/trunk/src/ShouldIt.Clr/Fluent/Be.cs&q=lang:c%23%20Fluent&d=3

What you should do when developing your own free interface or DSL (Domain Specific Language), which is also called, is to write tests first. Write tests about how you want him to behave.

 var q = Question.For(Site.StackOverflow) .WithTags("inteface", "fluent") .WithTitle("Are there any fluent interafces?"); 

And then start coding.

+2
source

I created a free claims library for .NET: Should a claims library (scroll down to see current examples).

StructureMap has a very sophisticated Fluent DSL for configuration.

FluentNHibernate is pretty good. It replaces XML-based mapping with free DSL.

C # (and other static languages) have a very good advantage for the Fluent API to support code completion (like Intellisense) to guide the user in composing what they intend.

On the other hand, with C # it doesn't matter that the language twist gets in the way. For example, you will often see things like Should().Not.Be.Null() , where it is better to see Should.Not.Be.Null .

+1
source

fluentAOP

Library AOP (Aspect-Oriented Programming), which allows you to implement using a free API. FluentAOP is primarily intended to simplify the adoption and use of AOP in .NET. It does not require XML files, attributes, or any other kind of configuration. Unlike most AOP implementations, its interception semantics rely solely on strongly typed method definitions and a free API.

Code example:

 // Note: line indented to improve readability var foo = new Proxy<Foo>() .Target( new Foo() ) .InterceptMethod ( f => f.Go() ) .OnBefore(()=> Console.Write("Hello World!") ) .Save(); // Result: every time Go() is called a "Hello World!" message is previously printed. foo.Go(); 

If the claims library

The If statement library provides a set of extension methods for tests for AAA and BDD style tests. It provides affirmations only, and as a result, it is an agnostic test runner. XUnit test direct fork statements. This project was born because test runners must be independent of statements!

Code example:

 var numbers = new List<int> { 1, 1, 2, 3 }; numbers.Should().Contain.Any(x => x == 1); numbers .Should().Count.AtLeast(1) .Should().Count.NoMoreThan(5) .Should().Count.Exactly(4) .Should().Contain.One(x => x > 2); 

Free statements

Fluent Assertions is a set of .NET extension methods that allow you to more naturally indicate the expected result of a TDD or BDD-style test. We currently use it in all of our internal and client projects and it is used in many open source projects. It runs on .NET 3.5, 4.0 and 4.5 (Desktop and Windows Store), Silverlight 4 and 5, and Windows Phon ...

Code example:

 var theObject = "whatever"; theObject.Should().BeOfType<String>("because a {0} is set", typeof(String)); theObject.Should().NotBeNull(); 

Fluentvalidation

A small validation library for .NET that uses a free interface and lambda expressions to create validation rules for your business objects.

Code example:

 public CustomerValidator() { RuleFor(customer => customer.Surname).NotEmpty(); RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name"); RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount); RuleFor(customer => customer.Address).Length(20, 250); RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode"); } 

TNValidate

TNValidate is a free .Net checker library. This allows you to write validation logic in a way that somewhat resembles a natural language. This not only makes it easier for developers to scan, but also means that non-programmers have the best opportunity to understand and change the restrictions that fit on the data.

Code example:

 // Basic validation. Validate.That(Email, "Email address").IsEmail(); // Chaining a couple of rules. Validate.That(Name, "Name").IsLongerThan(3).IsShorterThan(100); 

Fluent.net

The Fluent.NET library introduces extension methods to make .NET code more readable and more flexible for writing.

Code example:

 var x = Sequence.Create<int>(0, i => i); var pair = KeyValuePair.Create(1, "Hello World"); var strings = new[] { "This", "is", "a" } .AsEnumerable(); strings = strings.With("test"); 

Free NHibernate

Freely, without XML, compile safe, automated, convention-oriented mappings for NHibernate.

Code example:

 public class CatMap : ClassMap<Cat> { public CatMap() { Id(x => x.Id); Map(x => x.Name) .Length(16) .Not.Nullable(); Map(x => x.Sex); References(x => x.Mate); HasMany(x => x.Kittens); } } 

Fluent Configuration API

You can programmatically manipulate the default configuration classes used by the corporate library for the kernel, instruments, and all application blocks. A free interface, opened by the corporate library, is designed to facilitate this process. A free interface can be used for all customizable toolkit functions and for the entire corporate library of application blocks, with the exception of the Check and Application Blocks for Injection policy.

Code example:

 var builder = new ConfigurationSourceBuilder(); builder.ConfigureInstrumentation() .ForApplicationInstance("MyApp") .EnableLogging() .EnablePerformanceCounters(); 

Free automation

Simple, seamless DSL for automating web applications.

Code example:

 Test.Run("KnockoutJS Cart Editor", I => { I.Open("http://knockoutjs.com/examples/cartEditor.html"); I.Select("Motorcycles").From(".liveExample tr select:eq(0)"); // Select by value/text I.Select(2).From(".liveExample tr select:eq(1)"); // Select by index I.Enter(6).In(".liveExample td.quantity input:eq(0)"); I.Expect.Text("$197.70").In(".liveExample tr span:eq(1)"); 

Fluentdatetime

Allows you to write cleaner expressions and DateTime operations.

Code example:

 DateTime.Now - 1.Weeks() - 3.Days() + 14.Minutes(); DateTime.Now + 5.Years(); 3.Days().Ago(); 2.Days().Since(DateTime.Now); DateTime.Now.NextDay(); DateTime.Now.NextYear(); DateTime.Now.PreviousYear(); DateTime.Now.WeekAfter(); DateTime.Now.Midnight(); DateTime.Now.Noon(); DateTime.Now.SetTime(11, 55, 0); 
0
source

Source: https://habr.com/ru/post/1345686/


All Articles