The principle of shared responsibility - an example that is hard to see?

I just read about the principle of shared responsibility, and at one point, Robert C. Martin argues that it’s sometimes difficult to understand that the class has more responsibility.

Can anyone provide an example of such a class?

+4
source share
2 answers

Consider an HTTP class that has methods

  • Get (URL URL)
  • SendRequest (row request)

Both of these methods are HTTP related. However, Get and SendRequest have different levels of abstraction. Get can actually use SendRequest to send a GET request. Therefore, SendRequest must be in a low-level HTTP class, and Get must be in a high-level HTTP class that uses a low-level.

+4
source

This is funny because another StackOverflow user shows such an example a couple of 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 several separate roles:

  • This class is serializable.

  • This class can save its state in some storage

In many cases, this is not a good idea, because we cannot easily reuse this serializable object when we want to change our persistent storage from a simple binary file to an Xml file or to remote storage (for example, through WCF).

You can create subclasses, such as MyClassWCFSaver, but even then it is much easier to use the serializable class MyClass and the independent hierarchy MyClassSavers (with several different subclasses for xml, binary, or WCF repositories)

By the way, this is why in many ORMs we often distinguish entities from the repository (see the repository template ).

+2
source

Source: https://habr.com/ru/post/913818/


All Articles