How to apply Method Chaining in C#
Method chaining is a type of implementation pattern that we could reuse/recall a method a couple of times within a single object instantiation without limits. In wikipedia, it’s referred to as:
Also known as named parameter idiom, is a common syntax for invoking multiple method calls in object-oriented programming languages. Each method returns an object, allowing the calls to be chained together in a single statement without requiring variables to store the intermediate results.
If used properly, we can create a more efficient pattern which improves code readability in the long run. Another term for this implementation is called Fluent Interface which acts as if you were building a sentence.I first noticed this pattern when I was using jquery than I was using C#, so I got intrigued and curious whether the pattern was even applicable in the first place in my main programming language. Later on I discovered in some of my advanced projects where we use methodologies such as Unit Tests and doing some fluent mapping in NHibernate, Method Chaining becomes noticeable later on.
Okay, so why do we need to use method chaining exactly?
There are a couple of reasons why you might want to implement method chaining into your project or library you were working on. One of the few reason for this is its readability purposes. Ever since at the start we love to simplify our code through a lot of patterns. And from that idea alone, we now have dozens of frameworks and patterns thanks to our laziness and thinking that loves innovation.Here are other few reasons why we need to use method chaining:
- Allows you to create Domain Specific Languages (DSL)
- Improves reusability
- Direct
- Expressive
Getting Started
In this sample, we’re going to use C# as our programming language for implementing method chaining. Just simply create new project and select console app for this demonstration.Now let’s get started!
Starting out — the singleton pattern
To apply method chaining more efficient and cleaner, we must know the use of pattern known as the “Singleton Pattern”. Now what is a singleton pattern?I’m sure you’ve heard a lot from developers about the term “Singleton”Pattern that they were using from time to time.If you’re not aware of it, Singleton Pattern is one of the Design Patterns where it restricts the instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system.In a more simplified terms, a Singleton Pattern limits your object to only one instantiation. This is because every time we instantiate an object, it’s considered another object that was created behind the scenes even though we’re instantiating the same class. Singleton Pattern prevents that from happening.Let’s take a look at this example:
public class MySingleton {
private static MySingleton _instance = null;
public static MySingleton CreateInstance() {
if (_instance == null) {
_instance = new MySingleton();
}
return _instance;
}
}
In this example, we have the class called MySingleton and a method of CreateInstance. The purpose of this method is to leave the instantiation to it, effectively instantiating the object once only.Once _instance variable was instantiated with an object, we can no longer instantiate it again because it’s not null anymore. So when we use CreateInstance() to create an instantiation in both variables that we will use, it will still use the same instance that was created by the method, effectively referencing both variables with the same object instance.
Now why do I need this anyway?
This is done mainly to preserve and lock the values of the properties of that instance. When we do not implement singleton pattern, the values of your properties and fields would be swiped clean and can never be reused again as you’re effectively using another object as an instance.It’s worthy to take note that Method Chaining relies on fields or properties that you’re going to reuse behind the scenes in order to make it possible to produce an output using Chaining.
Setting up the method chain — proper class structure
Now let’s proceed with the main topic, setting up our method chain.Without further ado, I’ll show you some sample structure of method chaining. Let’s use the Dog class as a simple sample for our demonstration:
public class Dog {
private static Dog _instance;
public Dog() {
_instance = new Dog();
}
public static Dog Instance() {
if (_instance == null) {
_instance = new Dog();
}
return _instance;
}
public Dog Bark() {
Console.WriteLine("The dog barks!");
return _instance;
}
public Dog Eat() {
Console.WriteLine("The dog eats!");
return _instance;
}
}
And execute this class in our program.cs:
static void Main(string[] args) {
Dog.Instance()
.Bark()
.Bark()
.Bark()
.Eat(); //the dog barks 3 times and eats his food!!
}
And the corresponding output in console is:
Touche isn’t it?This is how you usually structure your method chain. One thing you’ll notice here is we let the Instance() static method do the instantiation for us. Although you could also do the instantiation on your own like so:
var mydog = new Dog();
mydog
.Bark()
.Bark()
.Eat();
I personally believe it’s more verbose and more understandable when you let the method do the instantiation to increase its readability. The choice depends on you.But I would like your attention to focus on the remaining two methods I haven’t explained: Bark() and Eat()This is the pattern that invokes method chaining. So both Bark() and Eat()methods were returning the instance where they were sitting. Now with that setup, you can chain them for whatever you like endlessly without limits!
A more practical sample — Creating a library
Now that we already know how to setup our method chain, let’s move on to more practical sample we could do to harness C#’s capabilities.We’re going to create our own Unit Test library. Unit Testing by definition is is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. Unit testing can be done manually but is often automated.So for our own Unit Test library, let’s consider this one as a starting point.Name it Assertion:
public class Assertion {
private static Assertion _instance;
private static int mygiven;
public static Assertion Given(int given) {
if (_instance == null) {
_instance = new Assertion();
}
mygiven = given;
return _instance;
}
public Assertion AreEqual(int equal) {
if (mygiven == equal) {
Console.WriteLine("They're equal!");
} else {
Console.WriteLine("Not equal!");
}
return _instance;
}
}
Now let’s use the library to test the results:
var given = 5 + 5;
Assertion.Given(given)
.AreEqual(10)
.AreEqual(5);
And our output in console is:
In the code, we’ve created our own Unit Test library and check whether the given value passes in our expected output which is provided in AreEqual()method.Through Method Chaining, our library is more fluent, understandable, and easier to read. You can also implement the Assertion library without using fluent interface or method chaining. But personally it’s more readable and understandable to use for consumers of your library if you’re gonna implement it fluently. Non-programmers can also benefit from using it since it’s easy to tell how to use it.
Wrapping everything up
I hope you enjoyed learning this lesson. This pattern can also be applied in other programming languages such as javascript since it’s where I first saw the pattern of method chaining.
Hello Eskiesrius; Your Dog class is not a singleton as long as the constructor is publicly available then the class is not a singleton.
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @eskiesirius! You have received a personal award!
1 Year on Steemit
Click on the badge to view your Board of Honor.
Do not miss the last post from @steemitboard:
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit
Congratulations @eskiesirius! You received a personal award!
You can view your badges on your Steem Board and compare to others on the Steem Ranking
Vote for @Steemitboard as a witness to get one more award and increased upvotes!
Downvoting a post can decrease pending rewards and make it less visible. Common reasons:
Submit