Writing code that tells you a story
Dilip Agheda
Software Engineer - Fullstack JavaScript | React | TypeScript | Node.js | Cypress | Selenium | C# | Test Automation | AWS
Uncle Bob mentioned in his book "Clean coder" about writing code that tells you a story. A story? What does it mean in the context of writing code?
What I took from that line is that
In this article, I want to share 3 practical way to achieve point 2 above. so let's get started.
Name appropriately
When you read an engaging novel, do you expect character's names as Mr X or Mr DD ? No right. Similarly, you want to name your variables, functions, classes etc to reflect the purpose and intention behind it. It is not difficult. Sometimes, It may be hard to come up with suitable names but It is possible to names things as close as possible.
For example, in the world of JavaScript / React, We often "map" an array. so good names could look like:
Define the boundary
You might be using TypeScript which is super awesome. TypeScript allows us to say what type variables are etc. But, It won't help you much to handle the business logic. All large scale enterprise software's have TONS of business rules.
You want to write code that self documents these business rules. While reading code, it should be obvious what's the intent.
For example, consider a function that determines an eligibility age to obtain a driver's licence. A business rule is that if a person is above the age of 18 and under the age of 90 then a person is eligible.
领英推荐
See how error conditions are tested right at the top. It clarifies the assumptions & defines a boundary in which the function operates.
testing error conditions is even more important when we build frameworks for other developers to consume. If other developers make wrong assumptions while using your framework then these errors give them a feedback and steer them in the right direction.
Never mix things up
I personally do not like to take short cuts and put in hacks. It might save you a time in the short run but bites back real bad in the long run.
In the SOLID principles, S is for separation of concerns. It simply means avoid writing spaghetti code. Put things where it belongs to. If you follow Domain driven design then It naturally encourages to build software in layers where there are producers and consumers.
Write classes that represents a business entity such as a Country or a Recipe. Then use the composition pattern to use smaller pieces to build bigger pieces.
In React, if you are fetching data from an API, you don't want to write the whole code in the useEffect. Instead use 2 different classes like so:
Summary
Alright folks. I hope it was useful to you. There is much more to writing clean code. I will share few more ideas in the next article.