In our continuing discussions on functions, I want to dedicate a small post to the Single Responsibility Principle, or SRP. SRP is an Object Oriented Principle (OOP). SRP basically means that a function or method should only be responsible for one thing. It should do one job, not two. Another way of stating this is that a function should have only one reason to change. Why is this important?
Imagine you have a function that does several things in your program. I like to call these “Super Functions”. When you have to update/change the code (and you will), the commingling of responsibilities will make it much more difficult to isolate and fix the problem or update the program. SRP allows for modularization and creates the ability to piece a program together with different sections of functionality. I think you will find that if you try to follow the SRP principle, you will make your life as a programmer much easier.
Another way that building functions with SRP in mind aids is in the actual design of the program. Programs are built to solve problems. Typically, your customer/client comes to you as the programmer and says something like, “Hey, I have this huge problem I need you to fix.” What typically happens is that huge problem is made up of a lot of little problems. Being able to break down problems and distill them into bite size pieces is a vital skill for the developer. This happens all the time in programming. For example, Zuckerberg never set out to create a global social media structure used by millions upon millions of individuals and businesses constantly. He simply set out to create something he could use to stay in touch with his sisters and it grew piece by piece from there.
SRP helps in this distillation of problems and tasks. You learn over time and experience how to break the huge problems down to their lowest common denominator and build functions that solve those little pieces to the much larger problem puzzle. Before you know it, you have solved the huge problem and created an elegant, efficient program that is easier to maintain and improve.
My goal with this post is that you begin to understand the SRP concept. It is actually a part of a larger OOP concept known as SOLID (another acronym for a possible future post?) SO try to keep the SRP concept in mind as you build your programs in whatever OOP language you utilize.