Did you know that DRY and SRP are very closely related?

Did you know that DRY and SRP are very closely related?

DRY stands for "Don't Repeat Yourself" and SRP stands for "Single Responsibility Principle". In practice, both of these principles are closely related. How? Let's see some examples of our daily development.

A very common thing we developers do is use static strings in different parts of the UI. i.e. a button, or a dialog title. Let's say we have two screens like the image on top. We can see that both the dialogs have the same buttons with the same text. It might seem logical to use only two variables for the two strings, after all, we don't want to repeat our code(DRY).

String positiveButtonText = "Yes";
String negativeButtonText = "No";

After a few iterations, there might be user feedback and the designer may want to change the button text from "Yes" to "Confirm" in the second dialog. Now as a developer, it's very easy for us. We have used a variable to store the string, so just changing positiveButtonText to "Confirm" solves the issue!

String positiveButtonText = "Confirm";

But Oops! After building the app the QA reports that the logout dialog's button text has also changed to "Confirm". We don't want that. Now we have to go and create two separate variables for the two dialogs and fix the issue. But why did this happen, we were supposed to follow DRY. Now we have to write even more code?

This is where SRP comes in. SRP states that a class or a module should have only and only a single reason to change. This applies to any piece of code, even the value of a variable. If we were thinking in SRP, the variable responsible for the button's text in the logout dialog has separate responsibility from the button text in the payment confirmation dialog.

Even though they might have the same value, they represent two completely different things. Their reason to change is also completely separate. So if we had followed SRP from the beginning we would have known that DRY does not apply here.

String loginPositiveButtonText = "Yes";
String loginNegativeButtonText = "No";
String paymentPositiveButtonText = "Confirm";
String paymentNegativeButtonText = "No";

DRY helps us in reducing changes to our codebase. So does SRP. In order to properly apply one we have to be aware of the other. SRP helps us determine whether we can apply DRY or not.

The above example might seem very silly and basic, but trust me I made these kinds of mistakes when I was a junior developer and I'm sure many other developers are making the same mistake right now as I'm writing this post.

So to avoid making these mistakes, always think of SRP when you are trying to apply DRY.

I hope you liked this post. Follow me to see more posts like this on your feed.



要查看或添加评论,请登录

社区洞察

其他会员也浏览了