Clean Code
21 Feb 2015
What is good code? This is a question that we ask every time we try to fix buggy software, refactor dirty code or comment on someone else's code, e.g: during a code review. The problem is that there is no perfect answer to that question. There is no widely-accepted metric for code quality. After all, software development is not an exact science. So everyone has a definition for "clean" code that is pretty personal, and very often quite controversial.
I don't think I'm too dogmatic when it comes to code writing. Now, I must say I'm a big fan of test-driven development:
- Write a tiny test that breaks
- Write a tiny bit of code that fixes the test
- Refactor
- Go back to step 1
However, I seldom follow this methodology to the letter. The tests I write are a little bigger than they should be; the code that fixes the test often does a little more than that; I usually don't refactor before the entire feature is implemented.
When I'm working on my own (not in a team) with a language or a framework that I know very well, I often don't write any test at all and I follow README-driven development:
- Write the README
- Write the code
And sometimes when I need to quickly get some hacky code out the door, I just put my Programming Motherfucker t-shirt on:
- Write some fucking code.
But as far as I am concerned, you don't need to follow any of these methodologies to write actual clean, good code. Again, dogma is not my cup of tea. However, during code reviews there are two very specific subjects on which I will not at all be open to discussion. Basically, I'm a fucking fascist about enforcing them:
- No code duplication
- Short functions
I'm pretty much open to discussion when it comes to writing (or not writing) unit tests, comments, picking variable names, or enforcing code style. But I will simply not negotiate with copy-pasting- and monstruous-function-writing developers. During a code review, if both parties disagree on the best way to write a piece of code, it often turns out it's for ideological reasons. And I'm all for taking the other's point of view, and even embracing a new code-writing ideology except when it comes to these two very specific points. For instance, I will have no empathy whatsoever with developers who claim that "this piece of code might be duplicated, but it's more explicit this way". Neither will I ever understand why "longer functions are clearer because you don't have to navigate between functions to understand what they actually do."1
Of course, I'm not the only moron who thinks code duplication and long functions hurt code quality, and there are many arguments against them. They were all summarised pretty well by Robert C. Martin and I don't think it's necessary to duplicate them here (pun intended). It's just that if you would like to challenge these assumptions and spend my time arguing against them, then I'm probably not the right person to review your code.
[1] That one is an actual quote.