业务对象上的静态工厂违反了单一责任原则?
如果我在业务对象上放置“数据访问”方法,是否违反了单一职责原则 (SRP)? 我的直觉是,如果 Load 方法存在于类本身上,那么 API 感觉更加用户友好,而不必猜测该方法恰好位于哪个类中?
例子:
public class Image
{
public static Image FromFile(string filename)
{
return ImageLoader.LoadImage(filename)
}
public void SetPixel(int x, int y, Color color)
{
}
}
Am I violating the Single Responsibility Principle (SRP) if I put "data access" methods on the business object? My gut feeling is the API feels more user friendly if the Load method is present on the class itself rather than having to guess which class the method happens to be in?
Example:
public class Image
{
public static Image FromFile(string filename)
{
return ImageLoader.LoadImage(filename)
}
public void SetPixel(int x, int y, Color color)
{
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我不认为这本身有问题,除了没有令人信服的理由让静态方法存在于 Image 类中(因为它不依赖于类中的任何内容,而是依赖于类本身)。
如果你最终得到一堆加载方法,它们在不同的类中可能会更好
i don't see a problem with this per se other than there is no compelling reason for the static method to live in the Image class (since it doesn't depend on anything in the class, but on the class itself).
if you end up with a bunch of load-from methods, they might be better in a different class
一般来说,我不认为知道如何通过单个路径(在本例中是从图像文件)创建您自己的实例并确保有效状态必然会给 SRP 带来压力。 如果您有大量此类方法,那将是一种代码味道,然后您应该根据提示将其分开。
In general, I don't think that knowing how to create an instance of yourself through a single path (in this case, from an image file) and ensuring a valid state necessarily strains SRP. If you had a proliferation of such methods, that would be a code smell, and then you should take the hint to separate things out.
我认为它是静态的这一事实使其不那么“过分”地违反 SRP,但我不是最大的 SOLID 纯粹主义者。 这些启发法不应该被过于虔诚地对待......
I think the fact that it's static makes it less "egregious" a violation of SRP but I'm not the biggest SOLID purist. These kind of heuristics shouldn't be taken too religiously...
在某种程度上,是的,但情况并不像你想象的那么糟糕。 任何原则都可能走向极端,以致令人不舒服。
问题是,如果稍后您希望将它们分开,因为您希望将该静态应用于其他图像,或者您想要实现可能适用于其他类型数据的更复杂的方法。
一般来说,重构 java 很容易,我建议你选择现在有意义的东西,只要记住每当它看起来可能导致你消除复杂性时就重新访问它。
In a way, yes, but it's not as bad as you might think. Any principle can be taken to an extreme that makes it uncomfortable.
The question is, what if later you want them separate because you wish for that static to apply to other images, or you want to implement a much more complex method that may apply to other types of data.
In general, it's easy enough to refactor java that I'd suggest you go with what makes sense now and just remember to revisit it whenever it seems like it might be causing you undo complexity.