Clean Code

A Handbook of Agile Software Craftsmanship

by Robert C. Martin, Prentice Hall

The book is all about writing software in a clean and professional manner. Additionally to explanations there are a lot of code examples to see how code can be improved. The examples and descriptions are mainly based on Java but can be used in other programming languages as well.

The sample code over here is just some pseudo code, so please don't think about the syntax too much.

What is "Clean Code"?

It's about the definition of clean code and quotes of some famous people in the field of software development what is important in their point of view.

Take away from the first chapter is the boy scout rule:

"Always leave the campground cleaner than you found it."

For the software development it means:Leave the code better than you found it.

Meaningful Names

Whenever using names for variables, functions, methods, classes or whatever they should be meaningful. In other words, the naming should explain what it is used for as concise as possible.

Instead of total=365 you can use daysPerYear=365.

Simply said: if someone at the other side of the world is looking at the code or you will look at it in a year: would it be clear what the thing is used for?

Functions

Functions (or methods) should do one and only one thing and they should do it well.

Therefore functions are usually small, they are well named and they are well organized.

Stepdown Rule:Code should be organized in a way, that you can read the code from top to bottom. Therefore functions are followed by the next one they are calling or next level of abstraction.

Comments

Comments should be reduced to the absolutely required minimum. In general they code should be done in a way, that it explains itself (proper naming, short and organized functions).

Do not comment-out code. Either you need this code or you don't need it.

// verify if the user is allowed to access the page and the page is existing
if (user->level > 20) and (page->id > 0) {
}

Could be done without comment as well:

if (user.permitted() and page.exists() ) {
}

Formatting

Keep files small and try to stay below 200 lines per file. The upper limit should be around 500 lines per file.

Vertical formatting should could functions together and variable declarations should be done as close as possible to the place they are used.

Horizontal formatting can be larger than 80 characters but should be limited to 100 or at maximum 120 characters per line.

Error Handling

Prefer exceptions over return values.

Do not return null and do not pass null to functions.

Testing

Write tests and production code at the same time (test > production > test > production > ...). Keep tests as short and clean as possible and apply the same quality measures to test and production code.

Classes

Keep classes small and apply the Single Responsibility Principle (SRP), therefore a class should take care about only one thing.