Explain the Single Responsibility Principle with a concrete example.

Get ready for your Object‑Oriented Programming Test. Use flashcards and multiple-choice questions. Each question includes hints and explanations. Prepare for your exam today!

Multiple Choice

Explain the Single Responsibility Principle with a concrete example.

Explanation:
The key idea is that a class should have one reason to change. When a single class combines business logic with persistence, two different concerns are tied to one place. If you change how business rules work, you might also need to adjust how data is stored, and if you alter storage details, you could inadvertently affect the business workflow. That coupling makes the code harder to maintain, test, and evolve. A concrete fix is to separate concerns: have a service or domain class that handles the business logic, and a repository or data-access class that handles persistence. The service focuses on what the system does, while the repository focuses on how data is saved and retrieved. The service can depend on the repository, but changes to storage won’t ripples into the business logic, and changes to business rules won’t force changes to persistence. Other options describe approaches that violate SRP by inviting multiple reasons to change or by combining unrelated responsibilities, or they focus on immutability, which isn’t the principle being tested.

The key idea is that a class should have one reason to change. When a single class combines business logic with persistence, two different concerns are tied to one place. If you change how business rules work, you might also need to adjust how data is stored, and if you alter storage details, you could inadvertently affect the business workflow. That coupling makes the code harder to maintain, test, and evolve.

A concrete fix is to separate concerns: have a service or domain class that handles the business logic, and a repository or data-access class that handles persistence. The service focuses on what the system does, while the repository focuses on how data is saved and retrieved. The service can depend on the repository, but changes to storage won’t ripples into the business logic, and changes to business rules won’t force changes to persistence.

Other options describe approaches that violate SRP by inviting multiple reasons to change or by combining unrelated responsibilities, or they focus on immutability, which isn’t the principle being tested.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy