Less lines of code doesn’t necessarily mean it is easy to understand for other developer to read. Making a code easy to read and understand is what every developer should aim for, and to me that is one of the better qualities of a good developer.
I understand, we thrive to write clean code and sometimes it comes at the price of readability, but that doesn’t have to be the case at all times. e.g I wrote a small article to simplify if-else blocks it looks clean and concise while maintaining readability.
In this post I’ll try to add a few tips as well which will try to achieve the aforementioned result. As always writing code is an art which evolves through practice and as any art form it is unique to the individual who wrote it.
I have used Typescript for the below example.
e.g. The below code receives a key and returns the corresponding month name. You can either use switch or if-else-if blocks to achieve this as shown. This works alright for a smaller size of the list, but what if the there are 50 or 100 values which you need to cater for.
Have a look at the below code. It’s super concise and does exactly the same thing as the previous snippet. In my opinion its elegant and doesn’t cause readability issues as well.
Give it a go next time you write an if else or switch statements. You’ll appreciate it.