I chose thevaluable.dev's example on Don't Repeat Yourself because it well demonstrates the concept. It talks about a shipment class on an e-commerce platform that's used to ship products to customers. First, it's configured for a single warehouse, but is later required to ship to 76 different warehouses with different details such as location and product amounts. Loops and other repetition logic are not the best as far as efficiency is required in this scenario. The programmer would have to re-write the code to meet the new demands. That is a lot of time wasted that could have been employed to fixing bugs or testing the code. This problem could simply have been fixed by creating a single abstraction capable of taking in different values yet delivering similar desired results without code duplication.
The blog also highlighted that the DRY concept was not only to be used in writing source code but also to anytthing that related to your project. "A system's knowledge is far broader than just its code. It refers to database schemas, test plans, the build system, even documentation". Whether it's database interaction to store or retrieve data in different parts of the code, a single component that performs this task should be used instead of copy/paste the source code.
When writing software, it's common to come across situations where the same functionality might be required. It's common to copy and paste the same code to varying locations to achieve the same task. Take an example of a coffee ordering system, the system captures a user's identity, financial data and their desired coffee type then generates an order number. Some customers may require that a receipt of their orders be printed out.
How and where would we get the data to print out on the receipt? There is a high possibility that we copy the code that identifies the user and their desired coffee type and then print it out. This is repetition and possible trap that we might find hard to get out of later. Instead, we could create a single user functionality such that printing a receipt is an option instead of making printing a stand-alone functionality. This way, we can also create other stores that use the same logic and we won't have to worry about making changes that only support one store and not the other.
I hope to use this concept in my future projects to avoid unnecessary repetition and time wastage. Clean code is easy to clean-up, refactor and update.
No comments:
Post a Comment