tags:

views:

51

answers:

2

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?

+3  A: 

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.

Sjoerd
?? Your reasoning seems more centered around the Single Level of Abstraction principle than around the Single Responsibility principle that the OP is asking about?
Marjan Venema
+1  A: 

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:

  1. This class is serializable

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

Sergey Teplyakov