开发者

Help understanding the Single Responsibility Principle [closed]

Closed. This question is opinion-based. It is not currently accepting answers.

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 5 years ago.

Improve this question

I'm trying to understand what a responsibility actually is so I want to use an example of something I'm currently working on. I have a app that imports product information from one system t开发者_开发知识库o another system. The user of the apps gets to choose various settings for which product fields in one system that want to use in the other system.

So I have a class, say ProductImporter and it's responsibility is to import products. This class is large, probably too large.

The methods in this class are complex and would be for example, getDescription. This method doesn't simply grab a description from the other system but sets a product description based on various settings set by the user. If I were to add a setting and a new way to get a description, this class could change.

So, is that two responsibilities? Is there one that imports products and one that gets a description. It would seem this way, almost every method I have would be in it's own class and that seems like overkill.

I really need a good description of this principle because it's hard for me to completely understand. I don't want needless complexity.


The 'responsibility' is defined in this principle as a reason to change. In this case the single responsibility of your class would be to import products. If the way of importing product changes, then the class should change.

The intention is to avoid having different things changing the same class at the same time. For example if your product importer class also defined its output format, it would then have two responsibilities, as likely the output format is totally unrelated to the mechanism of importing the data.

Now, that the class is huge and that getDescription() also sets a description are not a direct violation of the SRP, but of different principles. Namely, that you should avoid having huge classes (shows a lack of design) and each method should do a single thing (which would be kind of a more concrete version of the SRP.)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜