Click here to Skip to main content
15,885,182 members
Articles / Programming Languages / C#

Playing with fluent interfaces

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
21 Nov 2015CPOL2 min read 3.6K  
Using a fluent interface concept can be a good candidate to improve code readability.

A while ago I was reviewing one of our projects code and I noticed that it was very complicated and I had a hard time understanding what was going on and I was one of the senior developers of the team.I thought to myself maybe we could have a more readable approach in coding so that it would be easier to understand what is the intention of the code.

I think that using DSLs can help us to improve readability of our codes.As Martin Fowler teaches us in his brilliant book about DSL there are mainly two kind of DSLs internal and external and there's this concept of "fluent interface" that let us implement a kind of internal DSL.

Since I'm working with C# 3.0 and as far as I know C# is not a DSL friendly language I think using this fluent interface concept can be a good candidate to improve our code and have some useful DSLs in place.But how?

Suppose that we have a Login method in our domain that lets us to authenticate a user using a login name and a password,Something like this:

C#
UsersDomain.Login(username,password);

Actually every method like this is an action/command executing on a specific domain.Then we can have our domain specific language as follows:

On Domain Do Action With Parameters

And here's a C# example of the same:

C#
userDomain.Login().With((action)=>{action.Username=username;
action.Password=password;}).Do();

I know this seems very verbose in comparison with our traditional version but if we have thousands lines of code combining different domains and logic declaring everything in the latter way should help us understand the code better.

Let me show you a better example:

Suppose we have a mailing application that lets a client to send an email and here's our traditional approach to implement it:

C#
var mail=new Mail();
mail.From=fromAddress;
mail.To=toAddress;
mail.Header=header;
mail.Body=body;
mail.Send();

And here's the same using a fluent interface:

mail.Send().From(fromAddress).To(toAddress).Header(header).Body(body).Do();

I would like to know what you think of this approach. Please let me know

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Iran (Islamic Republic of) Iran (Islamic Republic of)
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --