静态帮助器类与实例类上的静态方法与扩展方法
我正在寻找解决以下问题的最佳实践方法。
我希望人们对他们将使用哪种方法以及为什么在以下场景中发表意见:
我有一个 Class
,当指定 DateTime 时,它由工厂实例化。
我应该使用哪种方法?
静态“助手”类:Class c = ClassHelper.GetClass(DateTime);
实例类型的静态方法:Class c = Class.GetClass(DateTime);
静态扩展类/方法:Class c = DateTime.GetClass();
目前,我更倾向于静态帮助器类,因为我从未采取过在实例类上使用静态工厂方法的方法之前,但对我来说在类上使用静态方法似乎有意义吗?
在单元测试或组织测试时我应该考虑什么?
我目前已经避开了扩展方法,因为我读到应该谨慎使用扩展方法,通常是在您无权访问要扩展的源代码的情况下?
干杯,
詹姆斯
I'm looking for a best practice approach to the following problem.
I'd like peoples opinion's on which method(s) they would use, and why, to the following scenario:
I've got a Class
which is instantiated by a factory when a DateTime is specified.
Which approach should I use?
static "helper" class : Class c = ClassHelper.GetClass(DateTime);
static method on the instance type : Class c = Class.GetClass(DateTime);
static extension class/method : Class c = DateTime.GetClass();
Currently I'm leaning more towards the static helper class as I've never taken the approach of having static factory methods on an instance class before, but it seems to make sense for me to do it with a static method on the class?
Are there any considerations I should be making when it comes to unit testing or organising tests?
I've steered clear of extension methods at the moment as I read that extension methods should be used sparingly, usually if you don't have access to the source you're extending?
Cheers,
James
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我的建议是遵循可能有效的最简单的事情 和代码内聚。
这意味着避免扩展和辅助类,只需将工厂函数放在
Class
类定义中即可。除此之外,这也是人们通常放置工厂功能的地方。My recommendation is to follow the principle of the simplest thing that could possibly work and code cohesion.
This means avoid extensions and helper classes, and just put the factory function in the
Class
class definition. Besides this is where people usually put factory functions.任何静态解决方案的问题是其他类可能会与您的类紧密耦合。
假设 ClassB 想要一个 Class 的实例。它在其方法中调用静态方法
Class.GetClass(DateTime)
。现在假设您想要独立于 Class 来测试 ClassB。 (或者,如果您不进行测试,您想在其他地方使用 ClassB 的不同实现来重用 ClassB,并且您不想引用整个层次结构。)您如何做到这一点?这个问题有多种解决方案。 IoC 容器 和 抽象工厂模式有两个。一般来说,它们涉及接口(它们是你的朋友)。他们也可能太过杀伤力;这取决于您的类的作用以及它将如何使用。
The problem with any of the static solutions is that other classes may become tightly coupled to your Class.
Say ClassB wants an instance of Class. It calls the static method
Class.GetClass(DateTime)
in its method. Now say you want to test ClassB independently of Class. (Or, if you're not into testing, you want to reuse ClassB elsewhere with a different implementation of Class and you don't want to reference the entire hierarchy.) How do you do it?There are multiple solutions to this problem. IoC Containers and abstract factory pattern are two. Generally they involve interfaces (which are your friends). They can also be overkill; it depends on what your Class does and how it will be used.