Wednesday, January 13, 2010

Can we drop the S in SOLID? (Or NTP!)

Maybe I just don't get the Single Responsibility Principle (SRP). Maybe it's just named poorly. I like the O, L, I, and D principles plenty, but my stomach feels anything but SOLID when I hear about the SRP.

According to Wikipedia, "[Robert C.] Martin defines a responsibility as a reason to change". I wish Martin had picked another, less useful word to redefine. So now, to even think the acronym SRP, I have to pause mentally before the R, and then mentally replace it with RtC (as in Reason to Change).

Even with this mental substitution, I still have problems with SRP. Is the SRP telling me that every one of my classes should have one and only one reason to change? How can this be, especially if a class has multiple responsibilities (as defined by Webster and Wirfs-Brock, not Martin)?

Here's my problem. In the Business Layer I like classes that resemble their real-world counterparts. For example, the Account object resembles a real account. The SRP principle would tell me that if my Account object had more than one reason to change, I should split it up. So if an Account object can calculate its balance, and perform a withdrawal, those are two places where the Account could change. Both of those responsibilities (think Webster) could change for any number of reasons.

I refuse to break up a domain-specific class just for some arbitrary limit on the number of reasons to change. We expect that change will happen. That's one of the reasons why we refactor our code and write unit tests.

Yay OLID. Boo S.

By the way, NTP from the title stands for No Teal Principles (where I've redefined Teal to mean Useless and Overly Restrictive).