Clean Code: Formatting (Source code structure)

“I also love just banging out code, saving, and having my editor clean up the formatting for me.” — T L Robinson

Pabashani Herath
Nerd For Tech

--

This article is the fourth of a clean code series. Let’s jump in and learn how to code formatting!

Why does code formatting matter?
Code formatting is about communication, and communication is the first order of business for the competent developer.
The type of coding and readability sets precedents that continue to influence maintenance and extensibility even after the original code has been modified.

Books would be hard to read if the line width was uneven, the font sizes were odd, and the line breaks were all over the place. The same goes for your code.
Keep the indentation, the line breaks, and the formatting compatible to make the code transparent and easy to read.

Messed code vs Formatted code

As I entered this chapter, I was very curious that this chapter really taught me something. Most formatting is automatically completed for us with current IDEs. You can also install software to support formatting, such as alerts or mistakes if anything isn’t formatted properly. (Will be discussed in detail.)

When we speak about formatting, the most important thing is not to respect a single style, but anywhere to respect the same standard. And if you’ve established your own formatting process, as long as it’s all right. To read and understand the code it is important to direct the formatting of the code.

You can pick a variety of basic rules that control your code format and then apply these rules consistently. If you work for a team or a committee, so a single set of formatting rules should be decided by the team and all participants should adhere. It lets you have an integrated method where you can use these guidelines for formatting.

Basically, there are various guidelines for how many lines of code a file can have and how many characters are optimum per line in this respect. You cannot locate the magic count, but you can feel it because there are so many lines of code and scrolling is irritating.

When you are formatting the code, you have to consider the below scenarios.

  1. Separate concepts vertically.
  2. Related code should appear vertically dense.
  3. Declare variables close to their usage.
  4. Dependent functions should be closed.
  5. Similar functions should be closed.
  6. Place functions in a downward direction.
  7. Keep lines short.
  8. Don’t use horizontal alignment.
  9. Use white space to associate related things and disassociate weakly related.
  10. Don’t break indentation.

Let's go through these standards in detail;

#01. Separate concepts vertically.

Concepts similar to each other should be maintained vertically. This law clearly would not work with different file definitions. But definitions loosely associated can then not be split into separate directories if there is no justification for this.
The vertical distinction should be a reflection of the value of both of these definitions are in terms of comprehension of the other in such a close relationship that they belong in the same source file.

Bad example:

import java.util.regex.*;
public class BoldWidget extends ParentWidget {
public static final String REGEXP = “‘’’.+?’’’”;
private static final Pattern pattern = Pattern.compile(“‘’’(.+?)’’’”,
Pattern.MULTILINE + Pattern.DOTALL);
public BoldWidget(ParentWidget parent, String text) throws Exception {
super(parent);
Matcher match = pattern.matcher(text); match.find(); addChildWidgets(match.group(1));}
public String render() throws Exception { StringBuffer html = new StringBuffer(“<b>”); html.append(childHtml()).append(“</b>”); return html.toString();
} }

Good example:

package fitnesse.wikitext.widgets;import java.util.regex.*;public class BoldWidget extends ParentWidget {
public static final String REGEXP = "'''.+?'''";
private static final Pattern pattern =
Pattern.compile("'''(.+?)'''",
Pattern.MULTILINE + Pattern.DOTALL
);
public BoldWidget(ParentWidget parent, String text) throws Exception {
super(parent);
Matcher match = pattern.matcher(text);
match.find();
addChildWidgets(match.group(1));
}
public String render() throws Exception {
StringBuffer html = new StringBuffer("<b>");
html.append(childHtml()).append("</b>");
return html.toString();
}
}

#02. Related code should appear vertically dense.

If clarity divides definitions, vertical density means close interaction. So lines of code that are closely connected should look thick vertically.

Bad example:

public class PropertyConfig {  /**
* The class name of the reporter listener */
private String m_className; /**
* The properties of the reporter listener */
private List<Property> m_properties = new ArrayList<Property>(); public void addProperty(Property property) {
m_properties.add(property);
}

See how the pointless comment in this example breaks the close connection between the two variables of instance.

Good example:

public class PropertyConfig { 
private String m_className;
private List<Property> m_properties = new ArrayList<Property>();
public void addProperty(Property property) {
m_properties.add(property);
}

It’s in an “eye-full,” in here. You can see that there are two variables and a process in this class, without your mind or eyes shifting too far. You have to use even more head and eye motion to meet the same degree of interpretation as the previous example.

#03. Declare variables close to their usage.

Variables should be declared as similar as possible to the spot they are used. On the 1st line you don’t want to declare a variable, and just use it on the 15th line.

#04. Dependent functions should be closed.

Dependent functions should be grouped together. The child’s function is preferred for the function name. This helps you to read the code very quickly without navigating too far around various places within the code.

If one feature calls another, it should be vertically similar and if necessary the caller should be above the street. This creates a normal flow for the software.

#05. Similar functions should be closed.

Some code bits tend to get close to other bits. They are conceptually related. The more affinity is greater, the less vertical space between them can be.

As we saw, this affinity can be based on a direct dependency, like a function calling another function, or a vector function. But other potential explanations for affinity remain. Affinity could be induced by a related activity as a set of functions.

Good example:

public class Assert { static public void assertTrue(String message, boolean condition) {
if (!condition) fail(message);
}
static public void assertTrue(boolean condition) {
assertTrue(null, condition);
}
static public void assertFalse(String message, boolean condition) {
assertTrue(message, !condition);
}
static public void assertFalse(boolean condition) {
assertFalse(null, condition);
}

The above functions are strongly related to each other since they share a similar naming scheme and modify the basic mission. It is secondary for them to name each other. They would both like to be close together even though they didn’t.

#06. Place functions in a downward direction.

We usually want dependencies in the call function to point downward.
We expect the most relevant ideas first, as in newspapers, and we expect them to be presented in the least polluting data. The low specifics are supposed to finish last. This helps one to skim the source files without having to dig into the information, getting the room from the first few functions.

#07. Keep lines short.

We will have horizontal lines that are wider than before since windows are larger than in previous days.
The norm for the former days was 80 characters long, but now 100–120 is okay.
The argument is that most people do not scroll to read our code horizontally.
Therefore better to keep lines short.

#08. Don’t use horizontal alignment.

We may not need to align the declarations of variables to be oriented horizontally.
We may not have to do, for instance, the following:

Bad example:

let num    = 1;
let value = 2;

We can keep it as:

Good example:

let num = 1;
let value = 2;

We can automatically allow a code formator to adjust this sort of spacing.

Bad example:

private   Long            requestParsingTimeLimit;
protected Request request;
private FitNesseContent context;
this.context = context;
input = s.getInputStream()
requestParsingTimeLimit = 900;

However, I considered this alignment to be redundant. The alignment appears to show the wrong stuff and pulls my eye away.

#09. Use white space to associate related things and disassociate weakly related.

Certain spaces should be in a horizontal code line between those entities. Spaces between variables and operators are nice places to bring in. There is also a good difference between operators and literals.

We require no space between the name of the process and the initial brackets. The distinction between operators and variables or literals is not so great.
We need space between the closing bracelets, the fat arrow, and the opening brace for arrow functions.

A clean horizontal formatting class, for example, may look as follows:

Good example:

class Calculator {
constructor(a, b) {
this.a = a;
this.b = b;
}

add() {
return this.a + this.b;
}

subtract() {
return this.a - this.b;
}

multiply() {
return this.a * this.b;
}

divide() {
return this.a / this.b;
}
}

We have a space between arithmetic users and no place between the name of the process and its open parenthesis.

There are also fewer than 120 characters in each line.

#10. Don’t break indentation.

It’s really important to respect a regular indentation in all your code, even though you want to break this standard occasionally. You will quickly detect the action done by a FOR or IF clause, etc. in compliance with this rule.

It is really quick to follow the same indentation anywhere with the new IDE’s and software.

For example:

Bad example:

const loop = ()=>{if(true){for(let x of [1,2,3]){console.log(x)}}};

It is much more difficult to read than:

Good example:

const loop = () => {
if (true) {
for (let x of [1, 2, 3]) {
console.log(x)
}
}
};

Code Formatting Tools

It can be taxing to recall all the rules on correct formatting. The fundamentals are simply protected and a complete report is already written. Therefore, you can use a range of tools to boost the automated and effortless formatting to reduce the effort on your part.

Online Tools

There are a set of tools to which you can add your code and distribute a more lovely version:

Code Editor Plugins

And also there are a lot of plugins/extensions which are coming with IDEs such as:

  • Prettier.io (works with Atom, Espresso, Sublime Text, WebStorm, VSCode, and more)

Prettier is a formatter of opinionated code. By parsing your code and re-printing with its own guidelines that take into consideration the maximum line length and wrapping code, it enforces a standardized template.

A strong and modern linter to prevent mistakes and implement your types of conventions.

TSLint is an extensible static analysis tool that monitors the readability, maintenance, and functionality of TypeScript code. It is commonly supported in the current editor and build environments and can be adapted to your own lint rules, setups and formatters.

The growing complexity of modern software systems also makes the code stable and maintainable. Code Metrics offers developers a deeper view of the code they produce. Using code measurements, developers can understand which styles and/or approaches can be reworked or checked more carefully. Project teams should identify possible threats, consider the overall project status, and monitor software development success.

Conclusion

Code formatting can increase the readability and interpretation of a code. At the start of the project, aim to identify and be ready to modify these regulations if necessary and if appropriate.

Note, the shortest rules are the best!

Don’t waste your time manually formatting your code. It takes time that can be better spent writing more code. Take advantage of the amazing modern tools out there.

--

--