Is there ever a “right way” to do something? Or is it all a matter of preference? Should we be dictating that code is written a certain way, and that any other way is wrong?
I am not proposing that we rid ourselves of the “shackles” of coding standards, or that we throw out everything we have learned about patterns that work, and those that don’t.
However, I think that we often miss the important part of best practices. And that’s the why.
I was recently talking with one of my coworkers about some code and he needed to create an if statement that only had one statement in it. As I watched him type it in, I wanted to scream! He had left out the curly braces.
I restrained myself and calmly told him that he should add in the curlies. I explained that it is perfectly legal without them, and the reasons I like to add them (readability and makes logic errors later less likely).
He said he had been wondering whether he should use them or not. He had seen some code without and thought that was a “best practice”.
When we have coding standards (which I think we should) or best practices, we should make sure to explain why we want the code that way. It is not always obvious. When the developer knows the why, he/she is much more able to determine when to break these standards/rules/practices (because sometimes it is best to do so).