I've just read about the Single Responsibility Principle and at one point Robert C. Martin states that it is sometimes hard to see that a class has more than one responsibility.
Can anyone provide an example of such a class?
Consider a HTTP class which has methods
- Get(URL url)
- SendRequest(String request)
Both of these methods have to do with HTTP. However, Get and SendRequest have different levels of abstraction. Get may actually use SendRequest to send the GET request. Therefore, SendRequest should be in a low-level HTTP class, and Get should be in a high-level HTTP class which uses the low-level one.
It's funny, because another StackOverflow user shows such example a couple hours ago in his question.
Consider this class:
[Serializable]
class MyClass
{
//Serializable fields
public void Save()
{
//Saving data into file
}
public void Load()
{
//Loading data from file
}
}
This class (MyClass) has few separate roles:
This class is serializable
This class could save his state in some storage
In many cases this is not a good idea because we can't easily reuse this serializable entity when we deside to change our persistant storage from simple binary file to Xml file, or to remote storage (for example via WCF).
You could create subclasses, something like MyClassWCFSaver, but even in this case it much easier to use serializable class MyClass and independant hierarchy of MyClassSavers (with several different sublcasses for xml, binary or WCF storages)
BTW, thats why in many ORM we often distinquish entities from repository (see Repository Pattern).
来源:https://stackoverflow.com/questions/3829306/single-responsibility-principle-a-hard-to-see-example