Understanding of How to Create a Fluent Interface

别来无恙 提交于 2019-11-27 23:46:35
Consult Yarla

One alternative could be to invoke all operations on Mpg() which will allow the other operations to be conditional.

This is already answered in SO with a code sample. Please refer to Conditional Builder Method Chaining Fluent Interface

The post indicates, instead of Interfaces, the same might be achieved using constructors, with a calling method that makes all others operations conditional.

Fluent API is a nice thing, but I would go a different way in your case. Building a car draws me more towards the Builder pattern. That way you would hide a car being composed in a factory (not the factory method pattern) which accepts commands like you have now, but do not accept questions.

No manufacturer lets you know details about their new car unless it is completed and prepared to be announced. So you would have to send a command like GetMyCar() for releasing a car first and it would perfectly make sense that if you call Mpg on unfinished car you would get an exception. And it would still look good if you use that fluent pattern.

var builder = new CarBuilder();
// each building method returns `CarBuilder`
builder.BuildFrames(size).BuildChassis().AppendWheels(4)...

Ok, that's my opinion. However there are two more suggestions for your current situation you can choose from if you don't like the builder.

1) If user calls Mpg before Weight and Fuel are set, thrown an exception with a message explaining the situation. Also add a proper documentation of the Mpg method.

2) Make a constructor take all required parameters for other properties. This is, in my opinon, a better solution than the first one, because is states from the very start what you can expect.

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