This text has one reason to exist. I want you to write smaller and simpler units of code. I want each unit of code to have only one reason to exist.
Code tend to turn more complicated than the complexity of the problem it solves. To prevent that we have patterns and practises for guiding us in writing simpler code.
One of my favourite guidelines is the Single Responsibility Principle. It is also worded as “one reason for change”, or as I put it here “One reason to exist”. It is a part, or the core, of other guidelines as well. Below I imagine my over worked piece of code, be it an object, function or script, that is loaded with far too much responsibility. I let it respond to my mistreatment of it.
Breaking Law of Demeter
My code: - Do I look bilingual to you? I do one interface, that is enough. Do not pass me something and expect me to know the language of its friends.
Having more than one return type
My code: - What will other code think of me if they can not trust me? I return one type, and only one!
My code: - Ok, it is fine that you ask me for help, but exposing my inner workings is not ok! How do you think that I can take responsibility for how they act? And it will make us totally entangled. I need to exist for my own sake, not for my network, thank you!
Sending in null, or data that has to be validated
My code: - Don’t I seem to have enough to do without you throwing garbage at me? I process data, give me data. If you need someone to sort out your nulls or hard to read json-blobs of the internet, write some other code for that, will you?
Having logic in the view
My code: - I do pretty. If you want thinking, ask someone that is easier to test.
Passing in a boolean as a parameter
My code: - Why can’t you make up your mind on how I should behave? Do you want to sneak in extra functionality? If you pass in a boolean you will force me to use a conditional somewhere inside, and that will cause problems. If you want me more flexible — relieve me of responsibility by passing in a collaborator instead of adding work for me by passing in a boolean.
My code: - There is no way that I can keep track of everywhere I am used. If they just stoped mutating me, they could each have a copy. But now I have to do their passive aggressive communication for them, so that they do not have to pretend that they are interdependent. I am both a state, and a way to send messages, that is one thing too much.
Code that has to deal with more than one thing will break under the stress of it. As will we developers trying to keep it all tidy. Bigger pieces of code can deal with bigger responsibilities (by delegation to smaller units of code). But still: Only one reason to exist for each piece of code. ps. There are probably more examples. Add a comment and I will let my code complain about that too.
Comment on the blog!
Create a comment by emailing me.
I will then add the comment to the post.