[Webinar Recording] Mistake-Proof Your Code with Fluent Interfaces

by Iveta Moldavcuk on 06 Apr 2017

Fluent interfaces are more than just a pretty way to write code. They can prevent errors, by ensuring your shared code is used correctly.

Our guest Scott Lilly will walk you through the topic of fluent interfaces and demonstrate how it can save you from needing to create the documentation that we never have time to write anyway.

Watch the webinar and learn:

  • What type of code can be improved with fluent interfaces
  • How to design the "grammar" for a fluent interface
  • How to quickly and easily write the code for your own fluent interfaces

Mistake-Proof Your Code with Fluent Interfaces on Vimeo.

Video Content

  1.  What is a Fluent Interface? (1:40)
  2.  When to Create a Fluent Interface? (4:36)
  3.  How to Build a (Fluent Interface)? (9:58)
  4.  Define the Vocabulary (Functions) (10:14)
  5.  Map the Grammar (15:50)
  6.  Summary (43:42)
  7.  Q&A (44:28)

Webinar Transcript

Introduction

Alex:

Hello everyone, and welcome to today's webinar, Mistake-Proof Your Code with Fluent Interfaces. My name is Alex and I'll be your moderator. I work as a software developer here at PostSharp, and I'm excited to be hosting this session today. I'm pleased to introduce today's speaker, Scott Lilly. Scott is a C# developer and leading practitioner, and today he is going to walk you through the topic of fluent interfaces. Before I hand the mic over to Scott I have a few housekeeping items to cover about this presentation. First, this webinar is brought to you by PostSharp, and PostSharp is a compile extension that adds support for patterns to C# and VB.

So if you are tired of repeating yourself in your code, you may want to check it out, as did folks at Microsoft, Intel, or Bank of America who have being using PostSharp in their projects to save development and maintenance time. By using our products, customers typically cut down their code base by 15%. So feel free to go to our website, www.postsharp.net, for more details, or to get a free trial. Next, today's webinar is being recorded and it will be available after the live session.

You will receive the email with a recording link after the session. So the last thing is we'd love to hear from you during today's presentation. If you have any questions for our speaker, please feel free to send in through the question window at the bottom of the player. We'll be answering questions at the end of the session, and if we don't get to your question during the webinar, we'll be sure to follow up afterwards via email. So without any further ado, I'd like to kick things off by welcoming Scott Lilly. Scott, it's over to you now.

What is a Fluent Interface?

Scott:

Okay, thank you Alex. Today we're going to talk about fluent interfaces, and especially how you can use them to increase your code quality. Here's an example of a fluent interface for sending an email. If you're not familiar with them, it's just a way to write your code so that it almost looks like a natural language sentence. You've got fluent email, dot create email using SMTP server from/to.

You could show this code to a business analyst or a software development manager, and they'd understand what the code is supposed to do. This is also good for any library code that you're going to write. I do mostly large projects for corporate clients, and those often take years of development, and have dozens of team members, some who leave during the project and some who come back, some new programmers. We don't want to spend a lot of time explaining our framework code, our libraries that we use.

And fluent interface can actually help them use our libraries much easier. It kind of instructs them as they go along. You can only call a function in a particular order, and it uses all the functions and sets all the parameters that our classes need. Now, I've got a quick question here. You don't need to answer it, you don't need to type in an answer, but how many attempts does it take to plug in a USB device? For those of us who work in technology, we've done this hundreds of times, and we know that the answer is three. Because you try to fit it in, you have to turn it upside down, still doesn't fit, turn it back upside down, and now it actually fits in.

Why is that? Because the USB ports were not designed to be mistake proof, and we don't want to do that with our code. We want to write code that is kind of like a power cord: It can only go in one way, it can only be used the correct way, so that way anyone who uses our code isn't going to have problems. So what we're going to cover in this webinar, first I'm going to talk a little bit about when you might want to use a fluent interface, so when you see this come up you can say, "Ah, I should think about adding a fluent interface here." And then we'll talk about how to create one, we'll define the vocabulary in our fluent interface, which would be the from, the to, the BCC, and all that.

And then we'll define the grammar, the way we can make it so that anyone who uses our classes with the fluent interface has to use it correctly. And then we'll actually write some code to see how you might do this with a sample report generator class. 

When to Create a Fluent Interface

1. You want to prevent running potentially-dangerous code

First, you might consider creating a fluent interface when you have potentially dangerous code that could be run, and you want to make sure that the developer that calls it can't do something incorrectly. For example, here's a function to delete accounts that haven't logged in for over one year. We've got a SQL connections, we create a SQL command, we've got our SQL command text, and we say, "Execute the non-query," except there's a problem here: This SQL statement doesn't have a where clause on it.

Now, I know no one here has ever done this, especially I've never done this, running a delete statement without a where clause, but you probably know someone else who has done this. And it would be nice if we could find a way to prevent them from ever doing a delete all, delete* from the table unless they actually wanted to do that. So what we can do with the fluent interface is we can build a DB cleaner class. After they set up their connection string information and they tell us the table they want to delete rows from, the only two options they have are to either call a delete with some sort of condition, or specifically call a truncate table. This is one way we can make our code mistake proof. No one could accidentally delete everything. 

2. Code must be called in a specific order (hidden requirements)

Another situation where we might want to create a fluent interface is when code has to be called in a specific order, kind of some hidden requirements. I know this is a violation of object-oriented programming principles, but here's an example of Microsoft doing something in the .NET framework that violates those principles. If we want to send an email, we have to create a new email message, and then we have to set these properties. We don't have any requirements for setting these properties, so we could forget to include the from, forget to include the to, and then when we get to the SMTP client, to actually sending out the email, what's going to happen?

Is it going to throw us a nice, clean error, or is it going to silently fail? Same kind of thing could happen with the code that we write. We create an instance of our object, you have to set a bunch of properties, or call a bunch of functions in a specific order, and then you can call the final function that does what you want it to do. With a fluent interface, we can build something like this so that you have to go in a specific order, you have to include certain things, even though this one has some optional parameters like CC and BCC. And you can't call descend until you've done all the required things, until you've set all the required parameters.

So this is another way we can keep our code mistake proof with a fluent interface. 

3. A function has many overloads, almost-overloads or optional parameters 

Of course, one way that we try to get around problems like this is we create a big function that has 20 parameters, and we end up with a third situation: You've got a function in a class that has 15, 20, 25 parameters, and then you have a bunch of overloads on it, and you have optional parameters, and you have some functions that are almost overloads but not quite, because they don't meet a couple of parameters, or this one needs an additional parameter, and your code just gets very messy that way. So I'm going to show some code here, this is going to be what we're going to work with, and this is a sample report generator that fits the third situation.

We have a create sales report, and we have to pass in this long list of parameters which I've actually seen some of these that are even longer, like I say, 20 or 25 parameters. And then, over time, we usually end up building other versions of this create sales report. So we have one here, create sales report for all categories, which has pretty much the same parameters, except it's missing the category parameter, because we want to include everything. Then, our manager says or the user asks us to add something that lets them create the sales report for all salespeople. So we have a function here that eliminates the salesperson ID parameter. And then eventually we'll have one that says, "Create sales report for all categories and all salespeople," that gets rid of the category ID parameter and the salesperson ID parameter. And we could end up with ...

I've seen some classes like this that get up to 30 or 40 functions that are basically the same thing. This is often happening in report generating classes, export classes, anything that gets kind of dynamic.

How to Build a Fluent Interface

Define the Vocabulary (Functions)

So what we're going to do is build a fluent interface for this fictitious sales report generating class. 

First thing we'll do is we need to know what type of functions we're going to have in our fluent interface. I break this down into ... I use the acronym ICE, I-C-E. We have some instantiating functions. These are the ones that actually create the report generator object. We have our chaining functions. These are the ones that let us add parameters to the object. And then we have our ending function, or our executing functions. This is the one that actually does something.

So if we look at the report generator class for our instantiating function, we're going to call it once at the start, and it has an action name, usually. I'm going to call this one "create sales report". And we can make it whatever we want. Then, we are going to determine what chaining functions we need. And this is where we're going to replace passing in a long list of parameters, or setting properties like we did in the email class. And for our sales report, we're going to have our parameters like from, to. If we look at the code, we've got our start date, our end date, our list of category IDs to include, our list of salesperson IDs to include, how we want to group it, how we want to sort it, so on.

And then we finally get to the ending function, and this is the one that's going to build the report. So all of our other functions before, we're going to say, "Start building the report with our create sales report," we're going to pass in all of our parameters, and once we get to the point where all of our parameters are set, we can say, "Build the report." So when we get the chaining functions, we're going to look here, since this is an existing class, at our parameter list. That's what we're going to use to actually find our vocabulary. So we're going to want to be able to pass in a parameter for the starting date, the ending date, the categories. Since we have different versions down here, we want some way of saying, "Create the sales report for all categories."

So we want to either be able to say, "Create it for all categories," or, "Pass in some category IDs." Same type of thing for the salesperson: We're going to want to have some way of telling our fluent interface, once we get to build reports, we should create it for all salespeople, or optionally, we can have a list of salesperson IDs that have been passed in. As we look at all the parameters, this is what I ended up building for my list of the vocabulary. For the instantiating, I'm just going to have the one function, create sales report. We could expand this and have other instantiating functions: Maybe you wanted to have create current month's sales report. And that way, it eliminates you needing to pass in the from date and the to date.

Or, you could have create end-of-year report, or create unchipped order report, and that would automatically set some of these other parameters for us. For our chaining functions, looking at the different parameters we had and different scenarios we had for our report, I want to pass in a from date, a to date. I want to be able to set it so I can include all salespeople, or so I can include specific salesperson IDs. And I put a little asterisk here to remind me that this one, I want them to be able to call multiple times. Same thing with include categories. And then down here at the include returned orders or exclude returned orders, I could've made that so it was just a boolean parameter that we pass in. It could be include returned orders and then pass in a parameter, but I like to have it a little bit more ...

The whole idea of the fluent interface is that it kind of sounds like a natural sentence. So I like to have different ones that include or exclude for the boolean properties, instead of passing in a parameter. It just makes the sentence read a little bit more naturally to me. And then at the end we'll have the build report function. This is going to return an object in our code here, but this could, in a real situation it would return maybe a PDF file or some other report-type object. You could even have multiple ending functions, you know, build PDF report, build SSRS report if you're using SQL server reporting services. Whatever you want, but just for this demo we're going to keep it kind of simple. So now that we have all the functions that we want to include in our fluent interface, this is kind of the vocabulary, the words we're going to use.

Map the Grammar

Now, we need to set up the grammar, which is the rules of what function can be called after which function. And this is how we're going to mistake-proof the code. We're going to have rules that you can't get to the build report until you've passed in all the required parameters. The way I do that is with a spreadsheet. You could do this with paper if you want. I just did it with a spreadsheet so it looks a little bit nicer. In the rows, you're going to include your instantiating functions and then all of your chaining functions. You don't need to include your ending functions, so here you've got create sales report as our instantiating, and then all of our chaining functions. For the columns, this includes all of the chaining functions and then all of the ending functions, the build report.

So we don't have create sales report in there, we just have the chaining and the ending. What we're going to do now is actually map out what can be called after each function, and I'll do that with the actual spreadsheet. So here, after create sales report, I'll just pull up a little screenshot there, after create sales report, the next thing I want to be called is from, and that's the only thing I want the developer to be able to call. So I just put a little yes in here to mark that after create sales report you can call from, and you can't call any of the other things. After from, the only thing I want the developer to be able to call is to. So I look in the from row, find the to column, and set that TS.

After to, I want them to be able to call include all salespeople or they could call include salesperson ID. So I go to the to row, look for the include all salespeople, set that to yes, and include salesperson ID, set that to yes. Now, for include all salespeople, the next thing I want them to be able to call is include all categories or include category ID. Because if they select include all salespeople, we don't want them to be able to include individual salesperson IDs. That's kind of useless at this point. So for include all salespeople, the functions we're going to allow next are going to be include all categories and include category ID. So I can go in there, in the spreadsheet, and mark those as yes. Now, include salesperson ID is a little different.

I want them to be able to call include salesperson ID a second time or a third time. Or, once they've added the last one, they can call include all categories or start including category IDs. So the spreadsheet for that is going to be yes for include all salespeople, because that's an option, yes for include all categories, and yes for include category IDs. And then I'd work this way for the rest of the functions, for the rest of the instantiating and training functions. And eventually, I would get a list that looks like this. So now I know the only time build report can be called is after this last include unshipped orders or exclude unshipped orders is called.

Because at that point I know we've gotten through every other required parameter correctly, and now we can do the ending function. So the next step ... I'll delete this one. So the next thing we need to do after defining the grammar is we need to give some names to some interfaces that we're going to create. This is how we're going to enforce the grammar, by having interfaces returned from our functions. And I like to make them nice and simple for the create sales report. The only thing you can do is set the from date, so I've named it "I can set from date". After calling from, the only thing you can do is call to, so I named that one "I can set to date". After you call to, you've got a couple of options.

So I named this interface "I can set all or one salesperson". And if you go down, let's see, here to include returned orders and exclude returned orders, they both can do the same thing. They both can call include unshipped orders or exclude unshipped orders, so they have the same name. Because what we're doing to do with this interface is say, "These are the functions you can call next." Since they have the functions they can call next, we're going to use the same interface, and this is how we build the grammar. 

Write the Code

So now, let's go into actually building a code. I'll start with a report generator class, and this is similar to the other one with some enums that I have for sorting and grouping, and I have no functions in this yet.

What we need to do is create a private constructor, because we don't want anything to be able to construct a report generator object other than our instantiating functions. That's the only way we're going to allow those to be instantiated. And then I'm going to create my first instantiating function, the create sales report, and for right now, I'm going to have it return the report generator object. This will be public static, because it's going to be like a ... It's a factory method, basically, the factory design pattern. And for right now, we're going to have it return a report generator, and that's all it's going to do. So when we call ReportGenerator.CreateSalesReport, it will instantiate our report generator and pass it back.

Then, I'm going to set up some ... Right now I'm just going to set up the from, the to chaining functions, and these will be public, and I'm going to have them return report generator, and this will accept the date/time parameter, and it's going to return this. So this is how we do the actual chaining. Each one of our chaining functions is going to get the value, and the final thing it's going to do is return the object that was called. So this is standard method chaining. If you've ever done anything like with a string object, where you do string.true.toupper.substring or something like that, that's method chaining, because the string.true returns a string so you can do another function that you can do on strings, like toupper. Toupper returns a string, so you can do another string function.

You can call another string function from that, like substring. And that's the method chaining that we're going to use. But for the fluent interface, the whole idea of the chaining function is to get parameters. So I'm going to need to create a private variable to hold the parameter value before we return the object. Then I'll create the to function, which will also return the report generator object, and we're going to need another private variable to hold our to parameter. And this will return this at the end, so we can continue the chain. Then eventually, we're going to get to our ending function.

I'm going to skip the other chaining functions for right now just so I can show how the method chaining works. And the ending function here is actually going to return an object. In reality, since it's the build report, it would probably return some sort of report object, but we're just going to do this for right now. But the build report function would then look at all the different parameters we've set, do whatever it needs to do, and then return the object. For the email fluent interface, that would actually be more of a ... When we had the send email, that would actually be a public void function, because that type of function is just going to do something. It's going to send the email and it's not going to return anything. The same type of thing with the delete.

If we were to build a fluent interface and the final thing was delete some rows from a table, that's probably going to be an execute non-query which we don't care about any return results, so it would be public void. But for this report generator one, we're going to assume that the final call, this build report, is actually going to return something. So now, we can look at some calling codes for this to see how the method chaining works, save our report equals report generator dot, and then IntelliSense shows me create sales report is the only function available, because it's a public static one. So I call that ... Now, if I press the period again, IntelliSense shows me the functions that I created, the public functions. I've got build report, I've got from, and I've got to. So I could call to, date/time, UTC now, from, date/time, UTC now... Add months, minus one, and then I can call the final build report.

 

So this is how the method chaining works, because create sales report returns a report generator, and the report generator has to, from, and build report as possible functions. But you might notice I did those out of order. My chaining, I want it to do from and to. That's kind of more of a natural sentence, but this still let me do it. That's because we haven't installed any of the grammar yet, we haven't set up the grammar with the interfaces. And this also still has the possibility of us forgetting to include from. Will the report still work? It depends on how well we wrote our build report function, but we're going to add the fluent interface to make sure that we call all of the correct chaining functions first.

Alex:

So Scott, just looking at this example, I'm wondering if there's possibly any tool that can generate some of this API code for us, like some initial code. It seems like it could be possible, just based on the grammar that you defined.

Scott:

That’s a good question, Alex. I started looking for something a few months ago and I didn't find anything, so I started a little project, an open-source project I'm going to build. But everything else has gotten higher priority. I'm hoping to get back to it soon.

Alex:

Well, that would be very nice, I think, to have something like that. Okay, well, looking forward.

Scott:

Okay, and at the end of the webinar, I'm going to have the link to a page on my site for all the source code. And if I have, or when I have that finished, I'll also include a link to that project. It's going to be up on GitHub.

Alex: Great, thanks.

Scott:

You're welcome. So another thing we can do, just a quick little thing to mention, is within our chaining functions, mostly all they're doing is setting parameter values and returning this. But we could add some additional validation rules in here. So we could say something like, "If to is less than from, throw new arguments exception," or something like this. Just another nice way to make our class a little bit more helpful to any other developers that might be using this.

But for right now, I'm just going to take these out. Now, I'm going to paste in all of the functions because I'm sure you don't want to watch me mistype commands on Visual Studio. So now I've got all the chaining functions in here, our from, our to, our include all salespeople, which is setting a boolean, our include salesperson ID, which adds the ID to a list, our group by, sort by, and so on.

So down here in the build report, we would look at all of those values that were set in these private variables, and use those to actually build the data set for our report. So the next step is we're going to create the interfaces. You could do this a little bit differently once you get some experience with it, but I kind of want to show step by step how this flows, how you could develop it. So what I need to do is I look at all of the interfaces here, and I'm going to just get a unique list of these, and I'm going to create those in the source code. For this sample, I'm going to create them inside the reportgenerator.cs file. You could put them in external files.

Normally, I don't like to put more than one class or more than one interface in a file. But these interfaces are only ever used by the reportgenerator class, so I'm not going to worry too much about that here. Then I'm just going to create public interfaces, I can set from date. And then set one for ... I can set to date, and again, I'm going to paste these in so you don't watch me type. But we're going to have one empty interface for all these different classes, or for all these different interfaces we've defined here in the spreadsheet. So now, these are all available as places for us to put our grammar in. Next thing we need to do is have this report generator class implement these interfaces, and I'm just going to paste in the names of all those interfaces up here.

Alex:

Okay, I've got another question: Maybe you can suggest any tools or practices, how to write this code faster. Maybe once you've finished the initial example, or just in general, some suggestions. Because it seems, while we still don't have this automated tool, it can be quite laborious to follow all this manually.

Scott:

Yes, the first time, if you set this up manually, it does take a bit of work. The idea is it's kind of an investment so that down the road everyone can use your library codes. But one thing you could do is instead of creating these functions, you could create the interfaces that are populated correctly, and I'll show you how we actually do that next. And then, have your report generator class implement these interfaces, and use a refactoring tool, like ReSharper, and say, "Implement the interfaces."

Alex:

Yeah, so it can generate at least a bit of that for you.

Scott:

Right, that would go and create all of these functions for you. You'd still have to go in, and have it return this, and set the private variables, but at least that way you're structurally building a lot of the code automatically.

Alex:

Okay, thanks.

Scott:

You're welcome. Okay, so now the next step is to actually have the functions return the correct interfaces. Because right now, they're returning report generator, which exposes every function in report generator. If we go back here to the calling code, and after I call to, IntelliSense shows me all the functions, and I can even call to a second time. So we want to use the interface to actually control what function can be called next.

And the way we do that is by going back to the spreadsheet, and seeing that create sales report, the interface that we want it to return is I can set from date. So I'll just copy that, go back in my code, and change its return type from report generator to I can set from date. It's still returning a report generator object, but it's casting it as an I can set from date, so the only thing that would be visible is any functions we've defined in the I can set from date, and this is how we're going to set up the grammar.

And I would go and do this for all the functions, change its return type from report generator, the temporary one we're using, to its actual correct one. And again, so you don't have to watch me type, I'm just going to copy and paste all that in. So now, each one of these functions, like conclude salesperson ID, it's going to return the object, but it's going to return it as an I can add salesperson ID or set categories, which is how we have include salesperson ID defined here in the spreadsheet.

So then, the final step is to actually add the functions that you can call next inside the different interfaces. So for example, I can set from date, if we look at the spreadsheet again, the only thing you can call is from. So I'll go up here in the code, find the from signature, I'm just going to copy that, and put it down here in the interface. So if we go back to our calling code, after I call create sales report, if I hit the dot, IntelliSense shows me the only function available now is from, so this is how we enforce the grammar. And if I do dot again, the only functions that are available are the ones that are available in object, because we haven't set up the rest of the interfaces.

So what I do next is for, I can set to date, we need to have it called the to function. So I'm going to add that to this interface. Just copy the signature of it, add it to the interface, and now if we go back to the calling code, and I type dot, IntelliSense shows me that to is available. So I'm going to just copy in all those, because we all know the worst way to mistype something is when you have hundreds of people watching you. And now, the interfaces are all defined. So now, we know the flow of what functions can be called after which function. And if we go back to the calling class, now we see to is available.

If I hit the dot again, IntelliSense shows me that my next available options are include all salespeople or include salesperson ID. So I'll use the include salesperson ID. Now, it shows me the only available options are include another salesperson ID, or start moving on to the categories. So I'll include another salesperson, then I'll say, "Include all categories." GroupBy, then I've got the SortBy next, and I'm going to say, "Include returned orders and include unshipped orders." And then finally, since all the parameters have been passed in and set for our class, we can call the BuildReport function, and that's how the fluent interface would work.

Alex:

Okay, I've got one, I suppose last question maybe from me. I was just thinking about LINQ, how it's kind of a fluent API is based on extension methods. So my question is how these extension methods can kind of affect our API that we design, our fluent API. On one side, you can make it extensible, but on another side, there's probably some consequences, and some probably things that we cannot ... Or we need to protect from properly, right, when someone tries to extend interfaces with extension methods that we didn't expect.

Scott:

Oh yes, I know the big problem I have in LINQ is when you have something in the middle of your LINQ chain that unexpectedly returns nul, so if you have a collection and you're doing collection.first, and you put in some sort of condition, and it doesn't have anything that matches that condition, yeah, then it returns-

Alex: Exception

Scott:

Yes, yes, because the rest of your chain, it says, "I've got nothing to work with." But the nice thing with the fluent interface is, since we're writing them and controlling them, everything is always going to return this at the end, so we know we don't have that possible null problem.

Alex:

Okay, yeah, so we need to pay attention to that.

Scott: Yes

Alex: Okay. Thanks.

Summary

So I'm just going to put this little closing slide out here: The next time you have a project where you're writing something that you think, "This is potentially dangerous," or, "Someone could misuse it, or miscall it, or not know how to use this function," especially if it's some framework code, or some library code, or something you're going to share on open source, don't write your code mistake possible, like the USB. Instead, consider putting a fluent interface around it for your facade, to make it easier to use, and also to ensure that other developers can only use it correctly.

 

 

Q&A

Here are Scott's follow-up answers to the questions. If the question was misunderstood, not answered completely, or if you can think of a different answer, please let him know by leaving a comment at https://scottlilly.com/FIWebinar.

Q: So from and to on create report are methods code after create report. If those values were required, can we provide these values as parameters to the create report method? I got the grammar should be present on the method name, but I understand also that the parameters of a function are part of the overall signature.

A: One possible thing we could do, so let's say we wanted to have something like CreateSalesReportForDateRange and include the from and the to in that, so then what we would do, we'd that here to the spreadsheet, I'd look to see what I can call next. So obviously, I don't want them to call from, I don't want them to call to. I want them to go onto the next step, which is basically the same as calling the To. So we would use the same signature as calling the to, and I would create another instantiating function, public static. See ... Get the correct interface, I can set all or one salesperson. Then, take our to parameters, and what we'd have to do is because this is a static function, we're going to need to a little bit of work on this.

But I would say you need to create another private constructor that takes those values, and set the parameters, set our private variables in here, and return new ReportGenerator with from and to, and I think that should work. So if we go back here, off our ReportGenerator I can see ... So I've got two options now: CreateSalesReport or CreateSalesReportForDateRange, and if I call that one for the date range, I can pass in the to date times. And now, when I hit the period, IntelliSense shows me that my next options are not from and to, but they're instead include all salespeople or include salesperson ID. So that would let our code look like this.

Alex:

Okay, thanks. I suppose that would be the answer, that basically, adding parameters to some of these methods is also a valid option. It's just probably, you need to pay attention not to add many parameters, because you go back to the same problem.

Scott:

Right, I generally like to keep one, maybe two parameters, sometimes zero. Like this include salesperson ID, we could also have created one that doesn't just take an integer, but it takes a list of integers. So maybe in the UI, the actual user is checking which salespeople they want to include, and we would pass a list of those IDs to the function. So then, we'd want an overload here, or we'd want another ... Include all these salespeople that accepts a list of integers.

Q: What's the reason to return type of an object instead of report generator and build report?

A: Because the build report is our final function, it's the one that's actually going to do something. So for this example, build report in reality would probably return like a PDF file, or some other type of object. You could also do this, like if you were doing, let's say, an average calculator and you wanted to do ... Your syntax would be like .includevalue.includevalue, and just, you're keeping all these. You keep passing in values, then your final function would be, your ending function would be calculateaverage, and that would return a double or whatever you wanted. So it all really depends on what your actual business purpose of this last function is.

Alex:

Okay, so that was just a sample object, in that case.

Scott: Right. 

Q: How would you have default values and avoid too lengthy code? Let's say for example that 90% of the time you would include all categories so I would not want to repeat that each time I use the FI.

A: You could make an instantiating function named „CreateStandardSalesReport()“ (for example). Inside that function, it would call the private constructor and set the default values. Its returning datatype would be an interface that is farther in the chain, past the functions for variables that were automatically set inside CreateStandardSalesReport.

Here is an example of how that might be done: https://gist.github.com/ScottLilly/85091b9f61e66256a69a7909a05337fd

I would change the interfaces, so the functions that can be skipped over are first in the „chain“. It’s easier to skip over the first five functions (for example), than to create interfaces and functions that let you optionally skip over the first two functions, then the fifth function, then the seventh function.
You might also want to integrate the Builder pattern, as mentioned in one of the questions below.

Q: How does this compare to the "Curiously Recurring Template Pattern" such as expressed here?

A: That pattern is an interesting way to do method chaining. Although, it looks like you will still need to create individual interfaces, to enforce any grammar rules.

Q: Can't you just use annotations to require a certain order and ensure parameters contain data?

A: Yes, you could use annotations on an entity, to ensure the required properties were set, before being able to execute a function. However, another developer could forget to set a property value, and the error will only be detected at runtime.

With the fluent interface pattern, other developers will have the additional help of IntelliSense, to lead them through the chain of required functions to call. They could still pass an invalid parameter to a function. However, they would not be able to skip over calling the function.

Q: Can we use Builder pattern where we create different set of Builder class for different values of Report properties?

A: Yes, you could combine fluent interfaces with the Builder pattern. That would be a good way to handle a situation where you have several common ways to set the values for the some of the chaining functions.

For example, if Accounting reports should always call IncludeAllSalesPeople, IncludeAllCategories, ExcludeReturnedOrders, and IncludeUnshippedOrders, that could have one Builder class that calls those functions. You could have a different Builder class to set the values to only include all the categories for items that are physical products (and not downloadable items), for the Shipping department.

Q: I would like to know about many Id's inside the filter, how to deal with this?

A: If I was building the ReportGenerator class for a real program, I would probably have a function for passing in a list of Salesperson IDs (as if the function was receiving a list of checked items in a datagrid that displayed the salespeople).

Inside that function, I would add the IDs from that passed parameters into the private _includedSalespoersonIDs variable, if that ID was not already in the list.

Q: Is this the only way to implement fluent interfaces? If not, what are the other approaches and how are they different from your approach?

A: This is the only way I’ve used. You might be able do something similar with extension methods that only work for specific datatypes (which would be the interfaces we use for the grammar). But, method seems less clear, to me.
If anyone is aware of a different method, please share it.

Q: How would you implement the IncludeSalespersonID function within the report class or option that are mutually exclusive when the report is actually being built?

A: When you create your fluent interface’s grammar rules, you should design it to prevent mutually-exclusive functions. For example, in the ReportGenerator fluent interface, you can call “IncludeAllSalespeople”, or you can call “IncludeSalespersonID”. You can call “IncludeUnshippedOrders”, or you can call “ExcludeUnshippedOrders”. You can only call one, or the other – not both.

Q: How exception handling works in fluent interface? How it works with optional parameters?

A: Exceptions would be caught at runtime. You could add parameter validation, that could throw an exception if the passed parameter was invalid. Also, when the ending function is called (BuildReport or SendEmail, for example), it could throw an exception.

The fluent interface can ensure that, when other programmers user your class, they will call the all the required functions to set the required parameters. However, if you do not include other data validation, they could set the parameters to invalid values – for example, setting the “to” date before the “from” date, when specifying a data range.

Q: Would it be possible to convert BDD scenarios to fluent?

A: This seems like it could be a great idea. I haven’t used SpecFlow, but a fluent interface would almost match with creating FitNesse fixtures.

This seems like it could be a great idea. I haven’t used SpecFlow, but a fluent interface would almost match with creating FitNesse fixtures.

If you show the users (or business analysts) the concept of method chaining, they should be able to create the grammar for you, using business terms. Then, you could use that to build the required fluent interfaces.

This is definitely an idea I want to think about some more. It may be a great way to deal with correctly understanding complex business requirements.

Q: If include All categories is optional, will the group by sort by be available to continue with the BuildReport? So, the order would include a Build report method for all functions that are deemed optional?

A: If you build the grammar to allow that, it should let you create that as a valid “chain”. I think the answer to the first question (<a href="https://gist.github.com/ScottLilly/85091b9f61e66256a69a7909a05337fd">see source code here</a>) will show how to do that.
Please let me know if that sample doesn’t answer your question.

Q: How to handle exception thrown by preceding method? How to stop chaining, or ignore error if not critical and continue chaining?

A: The chaining functions only set the values of the private variables, and “return this”. So, there should not ever be an exception – unless you add your own data validation in those functions. In that case, when the code is run, and an invalid parameter is passed, it will throw whatever type of exception you specify, and stop executing.

You could put logic into the chaining functions that would check if the passed parameter is invalid. If it is, instead of having the function throw an exception, you could have it determine a good (or default) value to use.

Q: Over time, let's say the ReportGenerator might add new functionality. Is it possible to have more than one path to reach the ending function? And how can we ensure maybe though unit testing that the chain leads to an ending function?

A: Yes, it is very possible to have more than one path reach the ending function. The ReportGenerator class has several possible paths (Include, or Exclude the returned and unshipped orders, for example).

Ensuring complete unit testing of all possible chains is interesting. If I was doing that, I’d probably to TDD, and use ReSharper (or some other static analysis tool) to show any functions in any interfaces that are not called. By looking at uncalled functions in the interfaces, that should inform us of any missing paths.

When I work on the fluent interface creating tool, that sounds like a good feature to add – automated generation of unit tests for each chain.

Q: I think you just need to get the result of IncludeSalespersonId inside the foreach and continue from there to avoid the casting.

A: I think this example is a little tricky, because you must either enter at least on salesperson ID (through IncludeSalespoersonID), or call IncludeAllSalespeople, before you can call one of the category-setting functions.

If you have an example that works, please share it at https://scottlilly.com/FIWebinar

Q: How would you go about baseclassing and extending this pattern with generics and inheritance is the essence of what I am trying to understand?

A: I have not tried to create a generic version of a fluent interface engine. Every time I’ve built a fluent interface, it has been very specific to one class (such as the ReportGenerator class).

If you needed to create “chains” for a class that were extremely different, you might want to have ReportGenerator as a base class, and create child classes, with their own interfaces that implement the different chains. For example, if you wanted to have a ManagementReportGenerator fluent interface for management reports, which might show different information, and have very different “chaining” options. You might also have an AccountingReportGenerator for the accountants, which might have a massively different fluent interface. Those would have their own sets of interfaces, but might use some functions from the BaseReportGenerator class.

Q: I want to call one interface or a different one according to a value previously set. For example, would this be possible? if IncludeSalesPersonID is called then AllCategories is selectable, and if they select allSalesPersons, then AllCategories is not enabled (to prevent a call from being too big).

A: Yes, you could do this. When building the grammar spreadsheet, in the row for IcludeAllSalespeople, don’t put a „Y“ in the IncludeAllCategories. Then, your interface for that row might be named IcanSetOneCategoryID. That interface would be defined to only have one function „IncludeCategoryID“, and its return datatype would be „ICanAddCategoryIDOrSetReturnedOrdersInclusion“.

 

About the speaker, Scott Lilly

Scott Lilly

Scott Lilly is a C# developer, creator of "Learn C# by Building a Simple RPG", and lean practitioner.
Scott develops line-of-business systems for corporate clients, and publishes videos and tutorials for C# developers.
Scott's blog.