👨‍💻
Software Engineering
Clean Architecture
Clean Architecture
  • Overview
  • Foreword
  • Preface
  • Part 1
    • Introduction
    • 1: Design & Architecture
    • 2: A Tale of Two Values
  • Part 2: Programming Paradigms
    • 3: Paradigm Overview
    • 4: Structured Programming
    • 5: Object-Oriented Programming
    • 6: Functional Programming
  • Part 3: Design Principles
    • Intro
    • 7: Single Responsibility Principle
    • 8: Open-Closed Principle
  • Part 5: Architecture
    • 22: Clean Architecture
Powered by GitBook
On this page
  • Historical Definition:
  • Definition:
  • What is a "module"?
  • Violations
  • Symptom 1: Accidental Duplication
  • Symptom 2: Merges
  • Solutions
  • Conclusion
  1. Part 3: Design Principles

7: Single Responsibility Principle

PreviousIntroNext8: Open-Closed Principle

Last updated 11 months ago

Historical Definition:

  • A module should have one, and only one, reason to change.

  • A module should be responsible to one, and only one, user or stakeholder.

A user or stakeholder are really referring to a Group - one or more people who require change. Group can be referred to as an Actor

Definition:

A module should be responsible to one, and only one, actor.

What is a "module"?

  • Simplest definition is just a source file, class, or a cohesive set of functions and data structures.

  • Cohesion is the force that binds together the code responsible to a single actor.

Violations

Symptom 1: Accidental Duplication

  • An Employee class for a Payroll Application has methods to calculatePay, reportHours, and save

  • These methods violate the SRP because they are used by three different actors.

  • If these methods were to share a common algorithm to calculate overtime hours, a change requested by one actor would unintentionally impact the other.

Symptom 2: Merges

  • Source files that contain many different methods often require merges when two developers (or teams) are working in the same file.

  • This is even more common when the methods are responsible to different actors.

  • When multiple people are changing the same source file for different reasons.

  • Solution: Separate code that supports different actors.

Solutions

Each solution moves the functions into different classes.

  1. We can separate the Functions from the Data using Employee, PayCalculator, HourReporter, and EmployeeSaver.

  2. Some developers prefer to keep the most important business rules closer to the data (e.g rich domain model). Employee becomes a facade, using separate classes internally to perform the operations.

Conclusion

  • The SRP is about Functions and Classes.

  • At the level of components, it becomes the Common Closure Principle.

  • At the architectural level, it becomes the Axis of Change responsible for the creation of Architectural Boundaries.

Single-responsibility principleWikipedia
Logo