JavaRush/Java Blog/Random EN/IntelliJ IDEA: Code Style and Formatting
Viacheslav
Level 3

IntelliJ IDEA: Code Style and Formatting

Published in the Random EN group
members
Modern tools make the development process easier. In particular, it is easier to monitor the style of your code, trying to minimize its “unauthorized” formatting. In this review, I propose to familiarize yourself with what tools the IntelliJ Idea IDE provides to the developer to make the code pleasant to read and easy to understand.
IntelliJ IDEA: code style and formatting - 1

Introduction

A programming language is very similar to the language people speak. The only difference is that this is a special language that is initially used to communicate with a computer in order to explain to it what we want from it. But there can be no one-on-one communication with a computer. Even when you started learning a programming language, you looked at a book or some educational resource like JavaRush. And in this source you saw code that a computer will understand. But you should also understand it as you gain knowledge of the Java language. As in any language, programming has some rules for forming code. For example, writing with a fence in polite society is considered bad manners, and in Java calling a method with a capital letter is a gross violation of the code style. The rules for formatting Java code are formulated in the Java Code Convention document . In addition, the code style can regulate smaller details, such as indentation. And when version control tools are used, imagine the whole nightmare when everyone saves a file either indented as a tab or indented as a space. What will it be like for someone who needs to check the edit in just one method, but the entire file will be changed due to the correction of spaces to tabs or vice versa. Naturally, as with ordinary language, style may vary depending on where it is used. For example, on the Internet you can find Google Java Style Guide or Twitter Java Style Guide . For this review article, we will need a test subject. Let's use the service of the Gradle project build system. It will allow us to create a new project using a template for a quick start. Gradle has a great plugin: Build Init Plugin . Let's go to the new directory and execute the command there: gradle init --type java-application After that, launch IntelliJ Idea. If you see a window with an already open project (you will see the code editor, the project structure tree), close this project using File -< Close Project. Now in the welcome window we will execute "Import Project"and import our new project. When importing, set the flag "Use autoimport". Let's figure out whether it is possible to somehow simplify life with the help of modern development tools.

Formatting Code in Idea

After importing the project, press the key combination Ctrl+Nand go to the class AppTest. This class is the default test class. It looks like this:
import org.junit.Test;
import static org.junit.Assert.*;

public class AppTest {
    @Test public void testAppHasAGreeting() {
        App classUnderTest = new App();
        assertNotNull("app should have a greeting", classUnderTest.getGreeting());
    }
}
What immediately catches your eye here? An annotation with a method declaration on one line, which looks ugly, agree. How to fix this? IntelliJ Idea has a menu section "Code"for various code manipulations. One of such manipulations is "Reformat Code"a key combination Ctrl + L. After application, the annotation will be on one line, and the method itself will be on another. It is worth immediately noting that this operation is performed on a selected section of code . And if there is no such thing, the formatting operation will be performed on all content. Let's now add a new test method:
@Test
public void testSummOfOddNumbers() {
	List<Integer> data = Arrays.asList(1, 4, 2, 3, 6, 7, 9);
	Integer result = data.stream().filter(number -> number % 2 == 0).reduce((n1, n2) -> n1 + n2).get();
	assertThat(result, is(12));
}
And two imports:
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
As you can see, the operation on Stream is placed on one line. But what if we want to make sure that methods whose calls are chained are always split at a point into new lines? On the one hand, we can do this manually. But remember that we want everything to work for us. After all, from time to time we will forget, and the code format will become different everywhere, and this is not good. It turns out that you need to edit the rule by which Idea performs formatting. Select the Idea item in the menu File -> Settings(or click Ctrl + Alt + S). In the search field in the settings window, write “Code style”. In the Code style section it is possible to specify settings not only for Java. But now we are interested in Java. As you can see, the settings are divided into several tabs. What's most useful is that the result of the change will be shown in an example on the right side of the window:
IntelliJ IDEA: Code Style and Formatting - 2
As you can see in the screenshot, we can specify the setting for "Chained method calls" as "wrap always", i.e. always split for merged method calls. Now let's click formatting again in the test and see that it really works! But sometimes it happens that there is a need to format some code outside of the general formatting rules. Let's set up formatting as follows:
IntelliJ IDEA: Code Style and Formatting - 3
To enable formatting to be disabled, support for disable formatting markers must be enabled in the Code Style section:
IntelliJ IDEA: Code Style and Formatting - 4
Now we can change the code of our test so that its formatting remains in the form in which we write it:
@Test
public void testSummOfOddNumbers() {
	List<Integer> data = Arrays.asList(1, 4, 2, 3, 6, 7, 9);
	// @formatter:off
	Integer result = data.stream().filter(number -> number % 2 == 0)
                             .reduce((n1, n2) -> n1 + n2)
                             .get();
	assertThat(result, is(12));
	// @formatter:on
}
Yes, if you notice: when you press Tab, Idea interprets it as spaces for you (default behavior). But you can change this there in Code Style:
IntelliJ IDEA: Code Style and Formatting - 5
As you can see, there are a huge variety of settings. You can read more about the Code style settings here: " Idea Help: Code Style ". There is another important formatting feature - import formatting. It is executed separately and is called "Optimize Imports"and is located in the menu item Code -> Optimize Imports(Ctrl + Alt + O). Import optimization removes unnecessary imports and also puts them in the correct order according to the settings in the Imports tab of the Code Style for Java settings. Also, if you want the formatting to happen automatically, the good news is that you can do it using the Save Actions plugin .

Distributing Settings to a Team

Great, we saw above that we can customize the formatting style to suit us. But how can this style be used in a team? Very simple. There are several options. The easiest one is to save the diagram. Open the Idea settings via File -> Settings (or press Ctrl + Alt + S). In the Code Style section we can see the inscription Scheme. This is our formatting scheme. By default, a scheme is specified with the name Default and next to it the annotation IDE: this means that this setting is only for our IDE, and it does not affect anyone. To make a “custom” scheme, click the button on the right to make a “duplicate” and give it a name, for example: JavaRush
IntelliJ IDEA: Code Style and Formatting - 6
After this we will be able to import or export the settings:
IntelliJ IDEA: Code Style and Formatting - 7
Another option is to import import Idea settings:
IntelliJ IDEA: Code Style and Formatting - 8
The third option is Settings Repository. For more information on using Settings Repository, see the documentation "IntelliJ Idea Help: Settings Repository ". On the topic of distributing a single style in the team, I also cannot help but note the good support for styles from the Eclipse IDE. To do this, you will need to install a separate plugin: open Idea settings via File -> Settings (Ctrl + Alt + S) and go to the Plugins section. To search for new plugins, click the button "Browse Repositories", after which we will find the Eclipse Code Formatter plugin in the search window.
IntelliJ IDEA: Code Style and Formatting - 9
Now, after installation, you need to restart Idea - this is a standard procedure. After that, in the same place, in the Idea settings, we will find a new section: “Eclipse Code Formatter” An example of a format file for Eclipse can be found here . It will look something like this:
IntelliJ IDEA: Code Style and Formatting - 10

Tightening requirements

In addition to the Idea tools, you can also use build system plugins to tighten the requirements. There is no way to check that a person used formatting. If there are 5 people in the team, it’s still possible. If the company has 100 people, it’s unrealistic. Yes, even five will be difficult to keep track of. And why waste time on this? It is much easier to prohibit the collection of a project if certain rules are violated. In fact, this is a whole separate topic called "Inspect Code". For the purposes of this article, I just want to show how it works. One of the most common plugins for Gradle (since it collects our project, if you remember) is pmd . To enable it, just go to the build script of our gradle project (the build.gradle file in the root of our project) and specify pmd in it next to the rest of the plugins:

plugins {
    // Apply the java plugin to add support for Java
    id 'java'
    // Check source code
    id 'pmd'
    // Apply the application plugin to add support for building an application
    id 'application'
}
Now we can set more detailed settings there:

pmd {
    ignoreFailures = false
    pmdTest.enabled = true
    ruleSets = [
            'java-basic',
            'java-braces',
            'java-clone',
            'java-codesize',
            'java-comments',
            'java-controversial',
            'java-coupling',
            'java-design',
            'java-empty',
            'java-finalizers',
            'java-imports',
            'java-optimizations',
            'java-strictexception',
            'java-strings',
            'java-typeresolution',
            'java-unnecessary',
            'java-unusedcode'
    ]
}
Even in our project, everything is no longer good. Let's run gradle build and get an error. What’s nice is that a report is generated during assembly. And if there are errors, we will receive a message like:

BUILD FAILED in 35s
6 actionable tasks: 6 executed
7 PMD rule violations were found. See the report at: file:///C:/_study/codestyle/build/reports/pmd/main.html
If we go to the report, we will see something like:
IntelliJ IDEA: Code Style and Formatting - 11
Moreover, in the Problem column there is a link to a description of the problem on the pmd plugin website. For example, for the error "headerCommentRequirement Required" the link goes here: pmd - CommentRequired . This error hints to us that our class does not have a JavaDoc. The presence of JavaDoc over classes can be configured using templates:
IntelliJ IDEA: Code Style and Formatting - 12
And specify the contents for File Header:
IntelliJ IDEA: Code Style and Formatting - 13
After this, we can turn the comment above the App class into a JavaDoc and see with a new Build that the error has disappeared.

Bottom line

Code style is important for a productive project. Beautiful code written according to general rules is the guarantee that your colleagues will understand it more easily and quickly, and will not say a couple of affectionate things about you. Given modern development tools, sticking to the rules is not so difficult. I hope this review has shown that this is indeed the case. Well, as usual, a little material on the topic: #Viacheslav
Comments
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet