简体   繁体   English

将构建器方法与服务方法相结合 - 不好的做法?

[英]Combining builder methods with service methods - bad practice?

This is a general patterns/best practices question.这是一个通用模式/最佳实践问题。 I'm using C# but I think it's equally applicable to Java and other environments.我正在使用 C#,但我认为它同样适用于 Java 和其他环境。 It's very common for libraries to expose a builder class that goes somewhat hand in hand with a more service-oriented class.库公开一个构建器类是很常见的,该构建器类与更面向服务的类在某种程度上是相辅相成的。 Take a hypothetical ORM that allows you to do this:假设一个 ORM 允许您执行此操作:

var sql = SQLBuilder.Select("*").From("Users");
var users = db.ExecQuery<User>(sql);

As a library developer it's tempting to combine these into a more fluent, discoverable API with only one object to be concerned with:作为库开发人员,很容易将这些组合成一个更流畅、可发现的 API,只需要关注一个对象:

var users = db.Select("*").From("Users").ExecQuery<User>();

Note that the difference is strictly in the API surface;请注意,差异仅限于 API 表面; under the hood we'd still have multiple classes with proper separation of concerns.在幕后,我们仍然有多个具有适当分离关注点的类。

One potential drawback of the second approach is testability.第二种方法的一个潜在缺点是可测试性。 In the first approach, it's much easier to stub out the service object.在第一种方法中,存根服务对象要容易得多。 But what if the library developer took care of this by exposing some sort of static TestMode property that can be configured on app startup or test setup and signals that the service calls should be recorded/faked?但是,如果库开发人员通过公开某种静态TestMode属性来解决这个问题,该属性可以在应用程序启动或测试设置时进行配置,并表示应该记录/伪造服务调用呢?

From a purist standpoint, other than testability, is there anything "wrong" with the second approach?从纯粹主义者的角度来看,除了可测试性之外,第二种方法有什么“错误”吗? I'm actually debating whether to do this in a couple libraries I'm working on, and my main red flag is that the first approach just seems so much more common.我实际上正在讨论是否在我正在开发的几个库中执行此操作,我的主要危险信号是第一种方法似乎更常见。

我认为第二种方法很好,只要公共 API 类只关心提供流畅的接口并正确地委派工作。

I actually intend to do take the second approach for the next version of my micro orm.我实际上打算在我的微型 orm 的下一个版本中采用第二种方法。 It didn't come up in my mind that testability would suffer and thinking about it right now, I think it won't.我没有想到可测试性会受到影响,现在考虑一下,我认为不会。 Because that fluent builder is merely a facade and at least the last part I'd probably implement it as an extension method which is easily testable因为流畅的构建器只是一个外观,至少最后一部分我可能会将它实现为易于测试的扩展方法

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM