La maggior parte degli esempi del mondo reale che ho trovato sono troppo semplici o troppo complessi per spiegarli completamente qui. Ti consiglio di consultare gli articoli di BlackWasp su SRP . (Gran parte del contenuto di quel sito può essere riassunto come mostrato di seguito.)
Dal uomo che ha creato il termine Principio di responsabilità singola:
... This principle is about people.
When you write a software module, you want to make sure that when changes are requested, those changes can only originate from a single person, or rather, a single tightly coupled group of people representing a single narrowly defined business function. You want to isolate your modules from the complexities of the organization as a whole, and design your systems such that each module is responsible (responds to) the needs of just that one business function.
Why? Because we don't want to get the COO fired because we made a change requested by the CTO. Nothing terrifies our customers and managers more that discovering that a program malfunctioned in a way that was, from their point of view, completely unrelated to the changes they requested. If you change the calculatePay
method, and inadvertently break the reportHours
method; then the COO will start demanding that you never change the calculatePay
method again.
Prosegue per ristabilire in seguito l'SRP in termini più semplici:
Another wording for the Single Responsibility Principle is:
Gather together the things that change for the same reasons. Separate those things that change for different reasons.
Wikipedia ha una definizione più semplice :
In object-oriented programming, the single responsibility principle states that every context (class, function, variable, etc.) should have a single responsibility, and that responsibility should be entirely encapsulated by the context. All its services should be narrowly aligned with that responsibility.
Che in particolare ti dice che puoi avere una classe che causa più modifiche, in base all'interazione con la classe (o il pulsante) specificato.
Prosegue con l'esempio di una classe di report:
Martin defines a responsibility as a reason to change, and concludes that a class or module should have one, and only one, reason to change. As an example, consider a module that compiles and prints a report. Such a module can be changed for two reasons. First, the content of the report can change. Second, the format of the report can change. These two things change for very different causes; one substantive, and one cosmetic. The single responsibility principle says that these two aspects of the problem are really two separate responsibilities, and should therefore be in separate classes or modules. It would be a bad design to couple two things that change for different reasons at different times.