Single Responsibility Principle - A hard to see example?

心已入冬 提交于 2019-12-01 19:29:09

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.

Sergey Teplyakov

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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!