Posts Tagged method chaining fluent interfaces chainability OOP exte

Die, void instance methods

Written much JavaScript? How about Ruby? Play with .NET extensions lately? Heard of “fluent interfaces?” What do these have in common? Let me give you a couple examples that may clue you into what I have in mind.

An illustration using System.Xml.Linq extensions in .NET:

return this
	.Settings
	.Descendants("settings")
	.Descendants("setting")
	.Where(element => element.Attribute("key").Value == setting)
	.Single()
	.Value;

A JavaScript illustration using the jQuery framework:

$("loginStatus").addClass("errorMessage").show();

If you guessed that it’s the wicked sweet feeling you get after using method chaining, you’d be right… well, almost. In fact, it’s the construct of method chaining, or simply “chaining.”

Now that C#, as of version three, can be written more functionally and has prototypical extensions methods, you’re going to see more and more of this. Not necessarily more complex examples like fluent interfaces (there’s a lot of code behind the scenes required to write fluent intercaces—more than the problem probably warrants in most cases), but chaining in general.

Regardless, a sure-fire way to impede chainability—and make babies cry—is to have void instance methods. Why have a void method when you could return the instance instead?

public class Thingamijig
{
	// Bad, like sweaty gym socks 

	public void DoSomething()
	{
		// something.Do()
	}

	// Good, like cotton candy perfume

	public Thingamijig BetterDoSomething()
	{
		// something.Do(), but better:

		return this;
	}
}

Never return null from an instance method. Always return this instead. Tell ’em I said so.

kick it on DotNetKicks.com

Leave a Comment