DEV Community

Discussion on: SOLID Programming (Part 1): Single Responsibility Principle

Collapse
 
annazubova profile image
Anna Zubova

That's actually a very good question! Breaking down code into functions/classes with single responsibility makes it easy to extend the code when needed as well as debug and modify. So it is a good practice to write smaller functions right from the start so you don't have to suffer when your code gets bigger. So the line is in the question: what does my function/class do? If it is one thing, you are good to go.

Imagine that you want to calculate the percentage of word's occurrences from AWS S3 bucket file instead of a local file. Since the functions are broken down, you just need to write a function that retrieves the content from S3 file (which you can also reuse in other tasks). Next you just combine it with percentage_of_word() function.

If you had it all in one function you would need to modify the code inside the function. But what if you wanted to be able to use both local file and S3? Now you would need an if statement which makes code bulky and slows it down. What if you needed even more content sources? Even more complexity to your function.

The Single Responsibility Principle is actually very connected with the Open/Close Principle which I am going to write next about. The principle says that the code should be open for extension and closed for modification. That is, instead of modifying the existing code it should be rather extended using already existing components and adding what is necessary.

Hope it answers your question!

Collapse
 
thinkdigitalsoftware profile image

Yes, it's a great point. I would have some if statements in there. My code tends to have a lot of those. I appreciate you writing these in such a short format because it's difficult to understand SOLID as a whole in large chunks