Whose Job Is It?
I wanted to share my experience that I had working on a recent project. If you’ve been programming for a while, you’ve definitely heard of the single responsibility principle. If you’re new to programming, maybe this is news. The principle states:
That every class should have responsibility over a single part of the functionality provided by the software, and that responsibility should be entirely encapsulated by the class
You could extend this concept to apply to not only classes, but methods as well. Should you have that one method that is entirely responsible for creating a database connection, connecting to a web service, downloading data, updating the database, uploading some data, and then doing some user interface rendering? What would you even call that?!
The idea is really this: break down your code into separate pieces of functionality.
Easier Said Than Done… Or Is It?
The idea seems easy, right? Then why is it that people keep writing code that doesn’t follow this guideline? I’m guessing it’s because even though it’s an easy rule, it’s even easier to just… code what works.
The recent experience I wanted to share was my work on a project that has a pretty short time frame to prove it was feasible. It was starting something from scratch, so I had all the flexibility in the world to design code however I wanted to. I really made an effort to keep asking myself this one question: Whose job is it?
Every time I asked that question and found that it was not my current method’s responsibility, I would ask “Is this class really responsible for that”? I’d either go make myself a new method in my class or I’d just go immediately make a new class with a single method on it. It seemed like a bit of extra overhead each time I had to do it, but was it worth it in the end?
Absolutely. After the project had proven itself and development continued on, I was easily able to refactor code (where necessary) and mock out functionality in my coded tests. Instead of trying to write test setup code that required a whack of classes I needed to initialize, I could mock out a couple of interfaces and test with ease. It was also really obvious which pieces were responsible for what functionality.
Final Thoughts
If you want to get better at following the single responsibility principle, I think it starts with one question: Whose job is it? Try it out!