Archive

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.

Download code samples.

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 http://scottlilly.com/FIWebinar.

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 http://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.

 

Design patterns are not just for architects. In fact, you already use Design Patterns but probably don’t know it. Observer, Proxy, Facade - these are patterns that allow us to better communicate our ideas with other developers. And once we understand the patterns, we can use solutions that people way smarter than us have already implemented.

In this session, Jeremy Clark takes a look at several Gang of Four patterns that we regularly use without realizing it. Don’t know who the Gang of Four is? Watch the webinar to find out.

Watch the webinar and learn:

  • What design patterns are (and what they are not)
  • How design patterns offer solutions to common problems
  • How we already use many design patterns, including Observer, Proxy, and Facade
  • How our modern languages support design patterns

Design Patterns: Not Just for Architects on Vimeo.

Download code samples.

Q&A

Q: Out of all the design patterns, how does a newbie decide which patterns to use for a given problem1? In other words, is there a way to filter out the patterns to arrive at a subset of suitable pattern?

A: This is a difficult question to answer. There are multiple ways to solve a problem. And there are also multiple design patterns to solve a single problem. The differences in the pattern have to do with what approach is taken. And this often leads to a different set of consequences. I would start by understanding the Gang of Four patterns. These are very common problems/solutions. And it will help understand the more complex patterns than you might run across. Just like learning anything new, start with the basics and talk to people or look online to see what people who are working in the same problem-space are doing.

Q: Does design patterns always obey SOLID principles? Or is it even important to do so?A: The SOLID principles are “best practices” in the object-oriented programming world. I don’t like to use the term “best practice” because that sounds like it is always the right answer. But with my experience (but success and failures), I’ve found that they are a good place to start. If I have a reason to not use the practice, I’m okay with that as long as I understand the pros and cons of a particular situation. In general, the Gang of Four patterns can help us adhere to the SOLID principles, but it all comes down to how we use them.

Q: Any example of factory or abstract factory which we are using and not aware of?

A: Unfortunately, I can’t think of one off the top of my head. But I have use the Factory Method to dynamically load objects from the file system. If you’d like an example, you can see my materials on C# Interfaces: http://www.jeremybytes.com/Demos.aspx#INT.

Q: Isn't Proxy pattern built-in pattern with tools like Visual Studio?

A: The implementation of the Proxy pattern that we looked at (accessing a SOAP service) is definitely built in to Visual Studio. But there are other scenarios we might want to use the Proxy, such as using a thumbnail image instead of bringing down a full image or the difference between downloading a song and streaming a song. So we do have certain implementations of patterns that are built into our language and tools. Some other examples in C# are Iterators (IEnumerable) and Observers (Event Handers / IObservable).

Q: How do we know that we need to use design patterns to a specific problem? Because most of the problems can be solved without using any design pattern.A: Learning about design patterns helps us see what solutions are available (and hopefully we can borrow someone else’s solution rather than creating our own from scratch). We can build a house by stacking bricks, but if we understand the patterns of walls, lintels, and foundations, we’ll end up with a much better structure. Programming patterns are the same way. I spent many years using patterns accidentally because I ended up solving these common problems. But once I could put a pattern name to a problem, I could look at how other people implemented the pattern. Sometimes I use those solutions, and sometimes I used them for ideas to incorporate into my own solutions. But that lets me use much better than what I could come up with on my own.

 

Q: There are plugins which allow patterns to be implemented in Visual Studio. Would you advise using them or rather learn the codes and implement them?A: I haven’t used the tools, so I can’t give an informed answer. As a general rule, I like to understand what the tool is doing before I use it. For example, I use Dependency Injection (DI) containers when I code, but I was not able to use them effectively until I understood what the containers were doing – and more importantly why. I would think it’s the same with pattern tools. I want to understand the patterns (particularly the “why”), and then I would be fine with letting a tool do the hard work for me. This would be similar to how I let Visual Studio create the SOAP proxy for me. I don’t need to understand all of the details (XML, HTTP, etc.), but I do need to understand why I’m using the proxy.

 

Q: What pattern should I use for creating exception handling library?A: Exception handling is a pretty big topic. It turns out that the built-in exception handling in .NET uses the Chain of Responsibility pattern (this is one of the examples I show when I have a bit more time to talk about patterns). When an exception is thrown, it looks for a catch block that can handle it. If it can’t find one in the current method, it walks up the call stack to the calling method. Then it just keeps walking up the call stack until something can handle it, or it drops off the end. (And this is why it’s a good idea to put a global exception handler somewhere in the code to make sure the user has a good experience.)

 

Q: Instead of using Proxy pattern for WCF services, I prefer use ChannelFactory object to use same object from the service without any MAPPER. Is there any other way to use Proxy for this case?A: As we saw in the definition of design patterns, there are a million different implementations. If there is a built-in implementation (such as the WCF Proxy in Visual Studio), I like to start there since it’s “free”. But if I find that my needs are a bit different (like I want to optimize for speed), then I’m free to look for different implementations or create my own. So there are lots of ways to use a Proxy in this situation. Unfortunately, I haven’t looked into them since the built-in one has worked for the situations I’ve needed.

 

Q: What about structure diagram and code?

A: Often when patterns are described in pattern catalogs, they are accompanied by a UML class diagram. Personally, diagrams often cause more confusion for me than help, so I tend to not use them. It’s easy for me to look at a class diagram and get stuck in a particular implementation when I really would rather understand the spirit of the pattern and the concepts behind it. Both the Gang of Four book and Head First Design Patterns include class diagrams (although the Head First book uses them for specific example code rather than the overall pattern).

 

Q: What pattern should I use for micro service implementation?A:Micro-services is a big topic. Looking for *a* pattern is like looking for a pattern for a web site. Generally, we would use multiple patterns to address the different problems that we are trying to solve. If we think of each micro-service as a self-contained application, then we can imagine using quite a few different patterns in putting it together.

 

Q: What is the difference between proxy and facade?

A: The main thing about design patterns is to look at the problem they are trying to solve. One way to think of the Proxy pattern is as a way to access a remote resource as if it were a local one (it’s a bit more general than that, but that’s the example we saw with the SOAP proxy). The Façade pattern is a way to reduce complexity by creating an easier way to interact with something (as we saw with the “foreach” example). The implementation of the SOAP proxy can also be considered an implementation of the Façade pattern since it’s wrapping the complexity of making the SOAP call (XML, HTTP, etc.). This is part of the fun when we start looking at patterns. We find that complex systems are often a combination of multiple patterns.

 

 

Q: When I have multiple patterns that can be used to solve a problem, how can I choose one, or can I combine them?A: This is one of those areas where we try to understand our tools better. There are multiple patterns that address the same problem (for example, there are many patterns that are variations of the Gang of Four patterns). In that situation, look at what the pattern is optimizing for. It may be addressing a particular consequence, such as performance or memory usage. If you are concerned about that consequence, then it may be a good choice. But if that consequence isn’t important to you, then something else may be better.

Q: Taking into account the example of IEnumerator and foreach, what would be the most correct to use?A: Since “foreach” gets compiled into the same code as using “IEnumerator” directly, I would use foreach. This makes our code more readable – and we need to make sure our code is readable by humans in addition to the computer. If there were a difference (for example, if the direct use were faster), even then I would look very carefully to see if that difference is important to me.

Q: You said foreach is a facade pattern. Is it also an iterator? Does it mean that any concrete implemenation can be a combination of multiple patterns?A: Yes, foreach is an example of the iterator pattern. In fact, I talk about this when I have more time to talk about design patterns. Many things we run across are implementations of multiple patterns. Another example is data-binding. This implements the Observer (when the UI elements change, the backing objects are changed) and also the adapter pattern (when a backing field is a number, it is displayed in the UI as a string). In reference to “foreach”, I usually call this an ‘Iterator” since that is its primary purpose – to iterate over items. The “Façade” pattern is more an implementation detail than the primary purpose.

Q: Which design patterns are useful in writing cross-platform code?A: There are a lot of patterns that we can use in cross-platform code, just like there are lots of patterns we can use in any application. The patterns we use depend on the needs that we have. For example, if I wanted specific UIs for each platform and wanted to share presentation code, I would look at various patterns that could help with loose coupling, such as Abstract Factory or Inversion of Control. But these aren’t strictly limited to cross-platform concerns.

 

About the speaker, Jeremy Clark

Jeremy Clark

Jeremy Clark makes developers better. By drawing on over 15 years of experience in application development, he helps developers take a step up in their skillset with a focus on making complex topics approachable regardless of skill level. He is a Microsoft MVP for .NET, and he has authored seven courses for Pluralsight, including "C# Interfaces", a course aimed at giving developers a clear understanding of abstraction. He loves speaking and has delivered over 200 technical presentations in the last 7 years in the United States and Europe. Jeremy lives in Southern California with 2 cats and a banjo. Jeremy's blog.

 

In this webinar, PostSharp’s founder and principal architect Gael Fraiteur demonstrates some of the most exciting new features of PostSharp 5.0:

  • Logging: PostSharp 5.0 comes with a fully revamped logging aspect, which allows for much more flexibility than before. Key new features include complete customizability, support for semantic logging, and super-fast performance.
  • Caching: You can now cache method return values and invalidate the cache easily, with custom attributes. PostSharp 5.0 will include support for MemoryCache and Redis, two-layered caches, and local caches with pub/sub invalidation.
  • Async methods: We have filled the gaps in OnMethodBoundayAspect and MethodInterceptionAspect for async methods.

Watch the webinar and see what's coming up in the new version:

PostSharp 5.0 Sneak Preview Logging, Caching and Async on Vimeo.

Download source code of the examples.

About the speaker, Gael Fraiteur

Gael Fraiteur

Gael has been passionately programming since childhood; building and selling his first commercial software at age 12. He is President and Chief Architect at PostSharp Technologies based in Prague, Czech Republic. Gael is a widely recognized expert in aspect-oriented programming and speaks at developer conferences in Europe and the United States.