• March 26, 2023
Format your code as a developer

Do you format your code as a developer?

It may seem unnecessary on the surface, but they will help you produce clean code.

Here are some tips for formatting your code effectively as described by Robert C. Martin:

1. Structure your code like a newspaper article

An article contains high-level detail in the introduction, with more specific information later on in the article.

The same goes for your code. For a class, your public functions should be high level at the top of your file and it should call other private functions which will do more detailed work lower down the page.

Formatting your code to read easily from top to bottom makes your code readable.

2. Vertical formatting

Your files should not be thousands of lines long.

Let’s go back to the newspaper example. Do you want to read a newspaper article that is thousands of lines long?

No. you want the article to get to the point. The same goes for your code.

If your class is too long, it is doing too much and needs to be split into multiple classes.

3. Horizontal formatting

Your code should be no more than 120 characters horizontally.

While this was a rule first introduced to prevent you from scrolling horizontally to read code. Nowadays, most people use a monitor that expands past the 120 character limit.

A long line of code is difficult to read.

Don’t be afraid to break a line of code down into multiple lines.

Look at the two examples below.

Example 1:

(false != $this->hasUserLoggedInThePast2Years) ? $loginMessage = 'Welcome back again!' : $loginMessage = 'You have not logged into the system in 2 years!';

Example 2:

(false != $this->hasUserLoggedInThePast2Years) 
? $loginMessage = 'Welcome back again!'
: $loginMessage = 'You have not logged into the system in 2 years!';

Which one is easier to read? They both do the same thing, just one is split into multiple lines.

Just because you are writing a line of code, does not mean it has to fill one line.

4. If you are working as a team, create format rules and stick to them

The above rules are just guidelines on how to format your code.

There are many rules you can follow:

  • The amount of spacing an indent has.
  • Naming conventions.
  • A blank space before a return statement.
  • Spacing between parenthesis in a condition.

The list is endless.

Rather than get stuck on all the ways you should format your code, it’s more important to decide on rules as a team and stick to them.

A project without clear formatting is messy and hard to read.