I recently held a presentation about Clean code at Sogeti and thought i’d recap the important parts in a post. The slides can be found on prezi.
The length of a method
A method should be as small as possible, about 3 to 6 lines of code. The method should never be more the 10 lines of code. It should also only do one thing.
Names
The name of a method should explain what the method does, and this gets simple since the method should only do one thing. Don’t be afraid to make the method name long, make sure to use a naming convention that allows multiple words in it.
The name of a variable should explain what the contents of the variable is. Bad name:
good name:
Do not use any abbrevations, they might be simple for you to understand but when another developer comes into your code he might not know what the abbrevation means.
Arguments
A method should not accept more than three arguments, if you go over that number maybe you should think about making an object that contains these arguments as a property.
Don’t use out arguments. When we read code we usually dont expect information to comeback from the arguments.
Don’t use booleans as arguments. if you do the method you’re writing will probably do more than one thing, depending if the boolean is true or false. And if you se a call to a method like this:
you will have to go into the method to know what it does with the true and false, instead of continue reading.
Comments
Do not comment code. The method name should explain what the method does. A comment will probably not get updated when the code is changed therefore the comment will be outdated and only confuse other developers. If you se outocmmented code just delete it. If you need it later it will always be in the version control.
If, else, while, foreach and try catch
The body of a if/else, while foreach and try catch should always be one line long and it should call another method. This is to keep the method small and the code will document itself with the methodname. Examples:
Do not return null
If a method encounters a problem and you decide to return null you’re going to have a lot of null checks in the code that calls this method. This is unnecessary, instead return a variable that is empty, for example:
if getEmployees() would return a empty list of employee when an error occured in that method we wouldn’t need to check for null and our methodcall could look like this:
These are only a few tips from clean code, i recommend you buy the book or take a look at Robert C. Martins code-cast about clean code.