Some quick guidelines to Clean Code

I recently read Clean Code by Robert C. Martin, and here is a very summarized compilation of tips/principles that I understoo or found useful.

Naming

Names should convey correct meaning. (descriptive and correct)
Names should be pronounceable.
Names should be searchable.

Functions

Functions should be small, < 10 lines.
Functions should do one thing and do it well.
A function that takes 2 parameter is good. A function that takes 1 is better. A function that takes 0 is best.
Avoid flag arguments (i.e. Boolean values), it shows that a function does >1 thing.
Functions should not have side effects (i.e. do things other than stated in its name).

Comments

Avoid comments if possible, your code should be explanatory.
Good comments: explaining intent, clarification of obscure parts, amplification of seemingly unimportant parts, TODO, warnings.
Bad comments: redundant, misleading, journal.

Formatting

Small files are easier to understand than big files.
Newspaper metaphor: Headline -> Quick summary/Gist -> Details.
Use blank lines to separate different concepts.
Code that is related should be close together e.g. variable declarations in a loop.
Use white space between words to emphasize relation.
There are no laws for indentation, just set rules within the team and stick to them.

Objects and Data Structures

Objects hide data behind abstractions and expose functions that operate on the data.
Data Structures are containers for data and have no meaningful functions.
Avoid train wrecks (i.e. someThing().anotherThing().lastThing().orIsIt()).

Errors

Use exceptions instead of return codes, this enables separation of error checking and function logic.
Write try-catch statements first (in line with TDD).
Write Unit Tests.
Three laws of TDD:
1 – You may not write production code until you have written a failin test.
2 – You may not write more of a unit test than is sufficient to fail, and not compiling is failing.
3 – You may not write more production code than is sufficient to pass the currently failing test.
Tests, like your production code, should be clean.
Single concept per test.

Classes

Classes should be small, just like functions.
Single Responsibility Principle (SRP), a class or module should have one, and only one, reason to change.
Classes should be open for change.

Good Designs (Rules by Kent Beck)

1 – Runs all the test
2 – Contains no duplication
3 – Expresses the intent of the programmer
4 – Minimizes the number of classs and methods

Successive Refinement

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s