Skip to content

Clean Code

Introduction

Clean Code is a term introduced by Robert C. Martin also known as Uncle Bob. Such a code:

  • Should be elegant - that is, easy to read and understand.
  • Should be consistent - each method, class or module should represent the same approach to the solution. The code should not be scattered and it should not be "contaminated" by dependencies and unnecessary details.
  • Should be taken care of. The developer who created the clean code took a lot of time to keep it organized and simple.
  • Passes all tests.
  • Does not contain duplicates.
  • Does not contain unneeded (unused) classes and methods.

How do you write clean code?

Meaningful names

The names of variables, classes or methods should indicate what they are responsible for.

Variable names

int d; // elapsed time in days
If you need to add a comment to explain what a particular variable or method is for, you're doing it wrong.

What should be the correct name for such a variable? E.g. like this:

int elapsedTimeInDays;

Class names

Class names should consist of a noun or a phrase with a noun, for example: Account,Customer or AddressParser. The class should not contain verbs in its name.

Method names

They should contain a verb like postPayment,deletePage or save. All methods responsible for getting or changing the field's value in a class should have a get or set prefix.

Number of arguments

Methods should take a small number of arguments. If you need to use a large number of arguments, it is likely that your code can be broken down into smaller pieces by applying some design patterns. The Builder pattern is a good example.

Method length

The body of the method should be as short as possible. Usually, if the body exceeds a length of about 20 lines (or, by convention, does not fit on one screen), we should make sure that the method does not have too much responsibility, i.e. does not do activities that should be performed by separate methods, or that such a method can be divided into several smaller ones.