Fluent API and Method-Chaining Style Usage

时光怂恿深爱的人放手 提交于 2019-12-12 18:19:48

问题


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.


来源:https://stackoverflow.com/questions/2403016/fluent-api-and-method-chaining-style-usage

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!