I recently read the book Clean Code, by Robert C, Martin, but I waited to comment on it until i saw how it fundamentally changed how I write code. I see there are quite a few blogs discussing it but i wanted to give my take on it, and specifically, in the short term, as I hope that other aspects will affect me more in the long run as well. (like improving my unit testing!)
The first powerful principle, laid down at the beginning is that “We are authors” and he develops this point two key ways that I thought i would share:
1. We read a lot of code.
Yes, its true. Whether like me, you are now reading others’ code as you have inherited their code, or you need to re-read your own code that you wrote 6 months ago and cannot remember, we are always reading our code. When we write complex code, long functions, etc, even our code takes way too long to remember what it does
2. Our code is our only reliable way to know what the code does. Comments are unreliable. Yes, its true – i see it in our application. I see that someone from our team changed code and left the now irrelevant comment in place. So, what does that mean? That the only effective and reliable way to document code is to write it in a way that it is readable. (yes, there are needs for comments on a class, but on specific lines of code, no)
So, how do we do that? Well, go ahead and read the book! But i will start and say – keep the functions short, keep the names of the functions descriptive so that the name of the function itself makes it clear what you will do in the function (and of course, don’t do too much in the function)
I like writing comments above lines of code to describe why I chose to implement something one way instead of another way that I was considering, or inform the reader of side-effects of the implementation. Also, sometimes if someone asks me a question about a particular line of code, I'll add my answer as a comment for other people who read that code in the future. Or if my code is based on some external source, like a technical specification, I'll add a link to the spec as a comment. Basically I like adding as comments things that cannot be understood or are difficult to understand from reading the code alone.
ReplyDelete