Join Reynald Adolphe for an in-depth discussion in this video Method chaining, part of C# Best Practices for Developers.
- [Instructor] Something that you always want to keep in mind when you're creating your methods, or just coding in general, is to avoid code duplication. And when we're dealing with methods, one way to do this is to by having the majority of the code that is duplicated in one method, and have other methods called the first, that has the majority of the work. So for example, we have two book actor methods here. We can minimize what's in here on line 47 through 49, and have the majority of the work on our second book actor method.
This is called Method Chaining. That is, when one method calls another method to get most of the work done. Let's go ahead and modify this to demonstrate what I'm referring to. In this method, I can just return the results of calling our second book actor method. And what I'll do, is just pass in an empty string.
And so I'll modify our second method to handle what needs to get done when it has a date, or if it's an empty string. So after our first line here where it has the details, which clearly was a duplication, I can type in theActor, and basically copy this on line 59, and just say is booked.
And now I'll put in an if condition. And if we have theDate and it is not empty, we'll do something here. Else will do something else. And what that else is, is we will return theActor, and can concatenate that with a period, and then that statement plus details.
And in our first condition, we'll have theActor +, and this is in the case where we know we have a date. So it's going to say Actor and their name is booked on the specified date, and along with the details, which is the warning indicating that they will not have a job if they start any trouble.
So in this case we've modified our second method, eliminated some duplication in our first method, which is up here. And this is an example of Method Chaining. So let's go ahead and Save this. And Test and make sure that everything passes as expected. I'll Right-click on TestBookActor, and Choose Run Selected Tests. It passes as we expected. And now let's test our method for a specified date.
That is selecting TestBookActor on specified date, and choosing Run Selected Test again. And that passes too. So in the context of best practices, use Method Chaining whenever you see the opportunity to reduce code that has been repeated. But definitely stay away from it if that is not the case, and it's just going to complicate matters.
- Naming and handling classes
- Running a unit test
- Using constructors
- Naming and handling methods, fields, and properties
- Using properties correctly
- Managing objects efficiently
- Common design patterns as best practices