Saturday, March 6, 2010

Method chaining issue

I met one interesting issue with method chaining today.
Method chaining is popular thing now, introduced by Martin Fowler and you probably seen it somewhere already, you can read about it here.
Generaly it looks like:

new HardDrive().capacity(150).external().speed(7200);

contrary to classic Java style

HardDrive hd = new HardDrive();
hd.setCapacity(150);
hd.setExternal(true);
hd.setSpeed(7200);


Today I found one funny issue with it. I got bug in this code:


parent.add(new Node()
.setName(name)
.setValue(value)
.setParent(parent))
.setId(id)


Of course, bug is trivial and easily found with debug. But what is bad with this bug, syntax is correct, so it is not discovered by IDE and it is not easily visible. For example, compare it to old style:


Node node = new Node();
node.setName(name);
node.setValue(value);
node.setParent(parent);
parent.setId(id);
parent.add(node);


Another minor bonus is that it is also easier to debug.

No comments:

Post a Comment