Fluent interfaces and leaky abstractions

2019-03-24 17:55发布

What is a fluent interface? I can't find a good definition of this, but all I get are long code examples in a language I am not very familiar with (e.g. C++).

Also, what is a leaky abstraction?

Thanks

8条回答
贼婆χ
2楼-- · 2019-03-24 18:36

Neal Ford does a nice job of explaining and giving Fluent Interface examples in his book the 'Productive Programmer'.

Traditional Object or 'bean' with getters/setters:

Car car = new CarImpl();
MarketingDescription des = new MarketingDescriptionImpl();
desc.setType("Box");
desc.setSubtype("Insulated");
desc.setAttribute("length", "50.5");
desc.setAttribute("ladder", "yes");
desc.setAttribute("lining type", "cork");
car.setDescription(desc);

Meet the same need with a fluent interface:

Car car = Car.describedAs()
  .box()
  .length(50.5)
  .type(Type.INSULATED)
  .includes(Equipment.LADDER)
  .lining(Lining.CORK);
查看更多
趁早两清
3楼-- · 2019-03-24 18:40

An object-oriented interface is fluent if methods that are executed for side effect return self, so that such methods can be chained together.

I first encountered fluent interfaces in 1990 when the Modula-3 Interface Police (I am not making this up) required all initialization methods to return the object initialized. I believe this usage predates the coinage of the term "fluent interface".

查看更多
登录 后发表回答