Search code examples
formattingchainingmethod-chainingcode-readability

What is the best way to format long chained methods?


What is the best way to format code with chained methods? Especially if it goes on for a long time? If you have a chain of three or so, you can put it on one line, but it gets cumbersome after you have a lot and it makes debugging difficult.

FYI, I'm talking about this: http://en.wikipedia.org/wiki/Method_chaining

Sometimes I write code like this (in Java):

DetachedCriteria criteria = DetachedCriteria.forClass(Taskdsr.class);
criteria=criteria.add(someRestriction);
criteria=criteria.add(someOtherRestriction);
criteria=criteria.setFetchMode(Criteria.DISTINCT_ROOT_ENTITY);

in place of:

DetachedCriteria criteria = DetachedCriteria.forClass(Taskdsr.class).add(someRestriction).add(someOtherRestriction).setFetchMode(Criteria.DISTINCT_ROOT_ENTITY);

Solution

  • You can format it across multiple lines:

    DetachedCriteria criteria = DetachedCriteria.forClass(Taskdsr.class)
                                .add(someRestriction)
                                .add(someOtherRestriction)
                                .setFetchMode(Criteria.DISTINCT_ROOT_ENTITY);