4 Ways to Format Your Code as a Developer to Make Your Code More Readable
Do you have formatting rules you follow as a developer?
They may seem unnecessary on the surface, but they will help your project look clean and readable.
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.
Nevertheless, 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.
(false != $this->hasUserLoggedInThePast2Years) ? $loginMessage = 'Welcome back again!' : $loginMessage = 'You have not logged into the system in 2 years!';
(false != $this->hasUserLoggedInThePast2Years)
? $loginMessage = 'Welcome back again!'
: $loginMessage = 'You…