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
	.Where(element => element.Attribute("key").Value == setting)

A JavaScript illustration using the jQuery framework:


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


1 Comment »

  1. I am constantly searching for brand spanking new info on this kind of essential issue,
    and am especially ecstatic when I discover blogs which might be well-written and well-researched.
    Thanks for featuring this exceptional info, and i also look forward to reading more out of your blog page in the foreseeable future. http://souforum.com/rss

RSS feed for comments on this post · TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: