tags:

views:

151

answers:

4

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)
   {
   }
 }
+2  A: 

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

Steven A. Lowe
+1  A: 

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.

John Feminella
@John you agree it is a call smell when you start adding a bunch of separate methods for this (even if they are in their own classes), that smell is precisely because the class is doing several things.
eglasius
@Freddy: What I'm saying is that while it's reasonable to say that hydrating yourself from an outside data stream is perhaps not your responsibility, a single instance of this isn't necessarily bad.
John Feminella
+1  A: 

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

Arnshea
+1  A: 

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.

Bill K