Tuesday, December 18, 2007

The beauty of return this;

As a beginner I was fascinated by the repeated append calls on the StringBuffer (Java) object. Especially because of the saving in the typing and no more string concatenation.

new StringBuffer("start").append("more").append("more")
Obviously the return statement of the append method should look like
return this;

Later I came across more interesting examples of this in the mock libraries like below.
Expect.Call(someObj.someMethod()).Return(anotherObject).Repeat().Once();

This time more than typing benefit what I liked about it is the readability of thecode. This is very close to the natural language translation of the above.
"Expect a method call someMethod on someObj. someMethod returns anotherObject. someMethod call is expected only once." Isn't that very close to how the code reads itself?

Look at this now.
 
"Create a new bug on build 45576 with description "this is really bugging ....". 
 
new Bug("new one").onBuild(45576)
   .withDescription("this is really bugging")
   .WithPriority("medium").reportedBy("QA")
and this
 bug = new Bug("new one");
 bug.setDescription("....");
 bug.setBuild(45576)......
 
We can improve the readability by adding 'And', 'With', 'To' etc.
Below I have added a creational method and used 'and' method to improve the readability a bit more.
 
 
Bug.CreateWithTitle("new one").onBuild(45576)
  .withDescription("this is really bugging")
  .WithPriority("medium").reportedBy("QA").and().assignTo("a dev")...

5 comments:

Mesirii@MG said...

This is just Method Chaining of a DSL.
See Martin Fowlers DSL Book (work in progress)

Michael

Aslam's Blog said...

Thank you for the reference. Is this the URL (http://martinfowler.com/dslwip/)? The page is not found. do you know about any alternate sources for the same.

Is method chaining specific to DSL?(sorry I am not familiar with DSL)

Phillip Calçado said...

Method Chaining is a way of implementing DSLs (like JMock does) or Fluent Interfaces. Martin's book draft has a lot of information (the URI you wrote is correct), althouh I sightly disagree with him.

Other text about those language adaptations:

http://fragmental.tw/research-on-dsls/language-adaption/

But method chaining is not used only for this, languages like Smalltalk uses this all the time without creating a new or specialized language.

Cheers

Phillip Calçado
http://fragmental.tw

KetanPadegaonkar said...

Returning 'this' that lets developers chain method calls takes a lot of java developer by surprise.

This has always been a convention in smalltalk, and is one reason why smalltalk code is beautiful, and the code talks to you.

cenkcivici said...

Fluent Interface