Command chaining

Even if you're still stuck using a non-dynamic language (Java, C#, etc), you can steal a trick or two from the other side. Command chaining is an easy practice that can really simplify your code. It's easy. Put return this; before the end of each method in your class. Just say no to void! Of course, you wouldn't do it on functions. They're supposed to return data. But following this practice for 'command' methods makes perfect sense, and allows calling code to be much cleaner. Compare:
Element para = new Element("p");
para.append("Hello World");
new Element("p") .set("class","song") .append("Hello World") .appendTo(document);
new Element("p") .set("class","song")
                 .append("Hello World")
#2 and #3 are far more readable. If you want to draw attention to the commands (say they aren't transparently obvious, or need inline comments), #3 is a better choice. If you want to focus on the surrounding logic, #2 cuts line usage down tremendously. Both remove repetition and reduce re-factoring costs. As a bonus, you don't have to clutter the scope with another arbitrarily named variable; you've created and finished with the object all in one statement. Like all coding practices, there is a short adjustment period while you get used to reading and writing this style; however, I'm confident you'll find it much faster to read and write code without that superfluous, repetitive text. DRY. Just say no to void. Be nice to your callers.

Published on

About Nathanael

Nathanael Jones is a software engineer, father, consultant, and computer linguist with unreasonably high expectations of inanimate objects. He refines .NET, ruby, and javascript libraries full-time at Imazen, but can often be found on stack overflow or participating in W3C community groups.


If you develop websites, and those websites have images, ImageResizer can make your life much eaiser. Find out more at


I run Imazen, a tiny software company that specializes in web-based image processing and other difficult engineering problems. I spend most of my time writing image-processing code in C#, web apps in Ruby, and documentation in Markdown. Check out some of my current projects.

More articles