Is a static factory on a business object a violation of the principle of single responsibility?

Am I violating the Single Responsibility Principle (SRP) if I put data access methods on a business object? I feel that the API feels more user-friendly if the Load method is present in the class itself, rather than guessing which class the method belongs to?

Example:

public class Image { public static Image FromFile(string filename) { return ImageLoader.LoadImage(filename) } public void SetPixel(int x, int y, Color color) { } } 
+4
source share
4 answers

I do not see a problem with this on my own, except there is no convincing reason for the static method to live in the Image class (since it does not depend on anything in the class, but also on the class itself).

if you end up with a bunch of loading methods, they might be better in another class

+3
source

In general, I do not think that knowing how to create an instance of yourself through one path (in this case, from an image file) and ensure the correct state necessarily creates SRP. If you had the spread of such methods, that would be the smell of code, and then you should take a hint to separate things.

+1
source

I think the fact that it is static makes it a less "blatant" violation of SRP, but I'm not the biggest SOLID purist. This heuristic cannot be taken too religiously ...

+1
source

In a way, yes, but it's not as bad as you might think. Any principle can be taken to the extreme, which makes it inconvenient.

The question is, if later you want them to be separated from each other, because you want this static object to be applied to other images, or you want to implement a much more complex method that can be applied to other data types.

All in all, it’s easy enough to refactor java, which I suggest you go with what makes sense now, and just remember to revise it when it seems like it might cause you some difficulty.

+1
source

All Articles