Fluent API and Method-Chaining Style Usage

2019-07-20 03:54发布

问题:

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?

回答1:

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).



回答2:

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.