Does the Single Responsibility Principle work in O

2020-02-01 02:17发布

I am struggling to understand how the Single Responsibility Principle can me made to work with OOP.

If we are to follow the principle to a tee, then are we not left with many classes, many of which may just have one method each?

If we don't follow the principle exactly, then what is the point in the principle?

7条回答
看我几分像从前
2楼-- · 2020-02-01 03:02

I like to state the single responsibility principle this way: "Every thing you write -- every module, class, interface, or method, should have one job. It should do the whole job and only that job.

Notice that some of these things you write are big (modules), some are small (methods), some are in between (classes), and some of the big things are made of smaller things.

That is not a problem, because jobs or responsibilities also come in various sizes and can be decomposed hierarchically. The job of the police force, for example, is to "protect and serve" -- one job, that decomposes into "patrol the streets", "solve crimes", etc., which can each be handled by a different unit. That creates the need for coordination (a different job), and the job of each unit breaks down into jobs for individual officers, etc.

For every big job, there are many ways to break it down into smaller jobs, and every one of those can be modeled by a software design that adheres to SRP and the other SOLID principles. Deciding how to break a problem down is a big part of the art of software design.

查看更多
登录 后发表回答