Saturday, August 25, 2012

Analogy - Single Responsibility Principle

"Single Responsibility Principle (SRP)" is one of those software design principles which are difficult to explain to a junior developer. And subjective-ness in the implementation makes it even more difficult. I tend to use analogies from real life to explain software design principles. Sometimes they  work, other times they don't. But in my small little world, they do help me remember these difficult software design principles. So let's build an analogy between SRP and restaurants.

In most restaurants, a waiter would help you choose food and take your order. Some other restaurant staff would serve you food that you ordered. And in the end, when you are done, some other staff would clear your table. This arrangement makes the service very effective and efficient. And this is a direct result of one person specializing in only one thing. Waiter specializes in taking orders and handing them over to kitchen. Some staff specialize in delivering food to tables. And some staff specialize in clearing the table. Because they are specializing in one thing (single responsibility), their job is simple and they are super efficient in completing their job.

If you correlate this to software design, then it's clear how a class that does only one thing is super efficient at doing what it does. Because the class is doing only one thing, you end up writing less code in a class, thus increasing the chances of writing code that is clean, modular etc.

There is an important link between SRP and service efficiency in restaurants. The interaction between different staff memebrs. You get a good service experience at restaurant because the interaction between various staff members is not broken. There is another hidden software design principle there. But that is for some other post.

No comments:

Post a Comment