views:

169

answers:

2

When programming against a fluent API or just using method-chaining, I've seen the style mostly like this:

var obj = objectFactory.CreateObject()
    .SetObjectParameter(paramName, value)
    .SetObjectParameter(paramName, value)
    .DoSomeTransformation();

What is the reasoning behind putting the dot at the beginning of the line instead of the end of the line like this:

var obj = objectFactory.CreateObject().
    SetObjectParameter(paramName, value).
    SetObjectParameter(paramName, value).
    DoSomeTransformation();

Or, is it merely a style thing that a team makes a consensus on?

+7  A: 

It's merely a style thing.

The advantage of putting the . at the beginning of the line is that it makes it more clear on a quick glance that this isn't a standalone method call.

For example, if you do:

var obj = objectFactory.CreateObject()
    .SetObjectParameter(paramName, value)

You can tell that SetObjectParameter(...) is a method being called on some other object, just looking at that line. Doing this:

var obj = objectFactory.CreateObject().
    SetObjectParameter(paramName, value)

Requires you to look at the previous line to tell. For example, this could be a formatting problem, ie:

var obj = objectFactory.CreateObject();
    SetObjectParameter(paramName, value);

(Here, SetObjectParameter would be a method on the current type, not on the type returned by CreateObject() - but, by looking at the second line, this is not apparent without the . beginning that line).

Reed Copsey
This rule doesn't just apply to Fluent interfaces, but more broadly to **all** method-chain statements, Fluent or otherwise.
Programming Hero
Yes - (and that's part of why I never actually mention "fluent" in my answer ;) )
Reed Copsey
Thanks for the clarification. I've editing my question accordingly.
Chris Dwyer
+4  A: 

Three reasons I can think of:

  • It's more obvious that each statement is a continuation of the previous one.
  • I find that Visual Studio's intellisense prefers it this way.
  • It's easier on the eye, at least in my opinion.
richeym
+1 for intellisense. IMHO this is the main reason for this convention. Methods are suggested when you write a dot. So if you want the method on a new line, the dot needs to be on this line also.
ewernli