Skip to content

Clean Code

Introduction

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

  • It should be elegant - meaning, above all, easy to read and understand.
  • It should be consistent - each method, class or module should represent the same approach to the solution. The code should not be scattered and polluted with dependencies and unnecessary details.
  • It should be well-groomed. Developer has spent a lot of time keeping it clean and simple.
  • It passes all the tests.
  • It does not contain duplicates.
  • It does not contain unnecessary (unused) classes and methods.

How to write clean code?

Self-aware names

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

Variable names

d = 10 # 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 such a variable be correctly named? E.g. like this:

elapsed_time_in_days = 10

Class names

They should consist of a noun or a phrase with a noun, such as Account, Customer or AddressParser. The class name should not contain verbs.

Method names

They should contain a verb like post_payment, delete_page or save. Methods responsible for getting or changing the value of a field in a class should have the prefix get or set.

Number of arguments

Methods should take a small number of arguments. If you need to use a large number of arguments, chances are your code can be broken down into smaller ones parts by applying certain design patterns. This pattern would be a good example Builder.

Method length

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