28 March 2006

On Method Chaining

In Eric Evans tutorial at SDWest the question of method chaining came up in response to some of Eric's Time and Money code.

The code which brought up the question was something like this:


CalendarDate workdate = CalendarDate.date(2006, 2, 15);
CalendarDate billdate = workdate.plusMonths(1).lastOfMonth();
int day = workdate.plusMonths(1).lastOfMonth().dayOfWeek(); //(contrived) method chaining
if(day == Calendar.SATURDAY || day == Calendar.SUNDAY){
billdate = billdate.plusDays(2);
}


The objection raised concerns the third line, where four methods are chained together (I purposely avoided re-using billdate to create this contrived example). So why is this okay? One simple reason, the method chain is completey stateless. That, to me, is the thing to look for when deciding whether it's "okay" to chain methods, if they can be explained entirely in terms of their inputs and outputs (that is, no side effects).

The second half of my rule for method chaining is just the opposite of the above, state changing methods should not be chained. That means I'd preclude the Smalltalk idiom of returning an object reference from setter methods with this rule. None of this:

myObject.setAttr(foo).bar();

At one point I had a good reason for precluding this second case, but it eludes me for now. However, at the very least, I would say the above is bad because it hides a state transformation occuring in "myObject". It is preferable to avoid chaining in these cases so that these state transformations are made explicit in the flow of the code... I think.

20 March 2006

Hello, world



/*A blog, just like a billion others, but this one is mine */
public class AndrewsBlog extends LemmingBlog{
Collection currentResearch;
Collection workActivities;
Collection lifeActivities;

public AndrewsBlog(){
currentResearch = new PriorityQueue();
workActivities = new RoleList();
lifeActivities = new WeakHashMap();
}
}