Fluent Interface(Method Chaining)

Barış Tutakli
2 min readMar 4, 2022

The first time I used FluentValidation library, I was fascinated by the readability of the code and the ability to call methods consecutively. After that the idea to create a custom fluent validation hasn’t come out of my mind. Then I tried to simulate Fluent Validation using C# extension methods a while ago. However, this one has not satisfied me. So, I’m going to explain to you the new version of the fake fluent validation sample. You can access the previous post link at the end of this post.

Requirements:

  1. Fluent Interface Design Pattern

A fluent interface is an API that depends on method chaining. Using fluent interface and method chaining, we can write the code below

instead of

2. Aggregate Exception Class

The aggregate exception class represents one or more errors that occur during application execution. I used this class to throw multiple exceptions at once. Aggregate exception class is derived by Exception class.

So, let’s start coding together😊

We store the errors thrown in this abstract class in _exceptions list. If the list is not empty, it throws errors found in the list. “return this” lets us connect multiple methods without having re-specify the object name each time. Methods use the same mutable object.

Concrete Validator

In this section, I created a validator class derived from Validate to define rules. For instance, “Hello World” can not be null and can not be empty. To test for thrown exceptions, I added “” and “null”.

Program.cs

Output

Exceptions:
Value can not be empty!
Value can not be null!

Do let me know your view on this 🙂 See you next time!

--

--