Look at these Java code snippet:
1:import java.util.Date; 2: 3:class Movie 4:{ 5: private Date exhibitionDate; 6: private Director director; 7: private Persister persister = new Persister(); 8: 9: public boolean isDirectedBy(String director) 10: { 11: // some code here; 12: } 13: 14: public void changeDateWithDirectorApproval(Date newDate) 15: { 16: // some code here; 17: } 18: 19: public void save() 20: { 21: persister.save(this); 22: } 23:}
At the save() method, persister takes care of the responsability to update the current movie, saving it at the persistent environment (a file, a DBMS, any data source, etc..) . Some may argue this class has two responsabilities: the Movie is responsible for its own behaviour AND its persistence. ButUncleBob has an interesting opinion about the Single Responsability Principle (SRP). It says Movie actually is not implementing persistence, the persister is a collaborator of the class. The persister is hidden from the client of the class, that is, is not part of the public interface. So, the lose coupling and the encapsulation is preserved. If the persister changes, the clients won’t be affected. It concludes SRP is about implementation, not interface. But imagine if you wanna find a movie, you can’t do movie.find() 🙂 . So, you have to deal with another collaborator who knows how to find a movie. Couldn’t be the Persister? No, because this one is hidden from the clients and if you become it public, you would fail with the information hiding principle. In this case, I think it’s better a Finder object. And you?