Start Small, jQuery uses Method Chaining
Chris Missal, December 11, 2008
Many articles this year have been on jQuery and if that's how you got here, I hope this article will help give you some ideas in other areas of programming.
I've noticed a few changes in the way I've been coding lately and I owe this method chaining in the jQuery's API. Here are two examples I have used method chaining in my projects. The first is from a ASP.Net MVC project in C#.
1 namespace MadeUpStats.Domain 2 { 3 public class Stat : IStat 4 { 5 public IStat AddTag(ITag tag) 6 { 7 tags.Add(tag); 8 return this; 9 } 10 } 11 } Usage: 1 var stat = statRepository.GetStatById(12); 2 3 stat.AddTag(Tag.Uncategorized).AddTag(Tag.Unknown);
This next one is from a PHP blog engine. (Code from this site actually)
1 public function getType() { 2 return $this->type; 3 } 4 5 public function getTopic() { 6 return $this->topic; 7 } 8 9 public function setType($type) { 10 $this->type = $type; 11 return $this; 12 } 13 14 public function setTopic($topic) { 15 $this->topic = $topic; 16 return $this; 17 } Usage: 1 $comment->setType($node["type"])->setTopic($node["topic"]);
jQuery isn't the first place that I've done this, but it is the first place that I've noticed how valuable it can be. Not only can it increase readability, it's commonly employed in fluent interfaces and Domain Specific Languages (DSLs). By understanding how to build an object that employs method chaining, you'll understand these concepts a bit better. I have found myself creating objects that have getters and setters and don't do much else, basically bloated DTOs. These type of objects should be caught and avoided, you'll find out they can become a headache down the road. These also go against the Principal of Least Privilege as well as YAGNI.
For more information on Method Chaining and Fluent Interfaces, I highly recommend that you check out these links:
- Martin Fowler's Domain Specific Language : Method Chaining - Excellent examples on method chaining techniques.
- Fluent Interfaces & Method Chaining - Explains the difference between the method chaining and fluent interfaces.
- Wikipedia entry on Method Chaining
Filed Under: C# Domain Specific Language Fluent Interfaces jQuery Method Chaining













