Question

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)
   {
   }
 }
Was it helpful?

Solution

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

OTHER TIPS

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.

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...

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top