C# 中的新样式
如今,流畅的 API 非常常见。最近,我在我使用的几乎每个系统中都发现了它们。大多数情况下,它们增强了可读性,但有时它们将我锁定在不灵活的规范中,使得理解它们构建的规范的运行时行为几乎不可能。对于如何创建良好的流畅 API 是否存在共识?使用流畅的 API 表示结构或规范的最佳方法是什么?
我最近注意到 NServiceBus 配置类中 Fluent API 的这种新颖变体:
class EndpointConfig : IConfigureThisEndpoint, AsA_Server { }
它使用多个接口作为一种线性 Fluent界面。我喜欢它,因为当我只想表达简单的需求时,它不会给我带来额外代码和上下文的沉重负担。在简单的情况下就足够了。不过,我不认为它会扩展到复杂的规格。您如何看待这种接口的使用?
您在 C# 中还使用了哪些其他新习惯用法?你在哪里使用它们?他们的优势是什么?你不会在哪里使用它们?另外,您如何衡量您正在考虑使用的习语的优势?
Fluent APIs are very common these days. Lately, I'm finding them in almost every system I work with. Mostly, they enhance readability but sometimes they lock me in to inflexible specifications, making understanding the runtime behavior of the specification that they build almost impossible. Is there a consensus on how to create a good fluent API? What are the best ways to represent a structure or specification using a fluent API?
I recently noticed this novel variant on the fluent API in the NServiceBus configuration class:
class EndpointConfig : IConfigureThisEndpoint, AsA_Server { }
It uses multiple interfaces as a kind of linear fluent interface. I like it because it doesn't place a heavy burden of extra code and context on me when I'm only trying to represent simple requirements. In simple cases that is adequate. I don't imagine it would scale to complex specifications, though. What do you think of this use of interfaces?
What other new idioms are you using in C#? Where do you use them? What are their strengths? Where wouldn't you use them? Also, how would you gauge the strengths of an idiom you were thinking of using?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我过去常常避免在指示不同行为的方法上使用布尔参数,例如,我会采用
int ExpenseComputation(bool useDiskCache)
并更愿意将其转换为
int ExpenseComputation(CacheType.DiskCache)
我最喜欢这个,因为当您调用
ExppressiveComputation(true)
时,如果不了解ExppressiveComputation
的所有信息,就不清楚true
的含义,而ExpenseComputation(CacheType.DiskCache)
为您提供了一个好主意。然而,对于命名参数,我发现使用第一个参数通常是可以接受的,并像这样调用它:
ExppressiveComputation(useDiskCache: true)
所以这是我最近为自己发明的一个习惯用法。I used to eschew boolean parameters on methods that indicated different behavior, e.g. I would take
int ExpensiveComputation(bool useDiskCache)
and prefer to turn it into
int ExpensiveComputation(CacheType.DiskCache)
I mostly preferred this because when you're calling
ExpensiveComputation(true)
, it's not clear what thetrue
means without knowing all aboutExpensiveComputation
, whereasExpensiveComputation(CacheType.DiskCache)
gives you a good idea.However, with named parameters, I find it often acceptable to use the first, and call it like this:
ExpensiveComputation(useDiskCache: true)
So that's a recent idiom I've invented for myself.