Video

Single Responsibility Principle in Ruby: One Reason to Change | Learn in 30 Seconds

You've seen this class. It persists the user, sends their welcome email, and builds the monthly report — all in one file:

class User ApplicationRecord
def send_welcome_email; end
def generate_report; end
end

Change the email template, and a report spec fails. Nothing about those two things is related, but they live in the same object, so they share its fate.

The Single Responsibility Principle says a class should have ONE responsibility — one primary reason to change.

THE REFACTOR

→ User — user data and persistence
→ WelcomeEmail — delivery
→ UserReport — reporting

Three classes, three distinct reasons to change. Now editing the email path touches the email class, and the other two specs don't even need to run differently — they were never coupled to it in the first place.

THE MISREADING

SRP does not mean one method per class, and it doesn't mean every class should do one tiny thing. A class can hold a dozen methods and still satisfy SRP, as long as they all serve the same job. Taken too literally, the principle produces a codebase of anaemic single-method objects that's harder to navigate than the thing you started with.

The useful test isn't "how many methods does this have?" It's: *who would ask me to change this?* If the answer is "marketing wants a different email, and finance wants a different report," that's two reasons to change, and they belong apart.

Rails gives you natural homes for this: mailers, service objects, query objects, serializers, presenters. The model doesn't have to hold everything just because the data lives there.

—
#Astmation — #software #systems, #automation, and #AI-powered #applications.
Build. Automate. Evolve.
https://astmation.com/


Watch on YouTube

Back to videos