CodeGym/Java Blog/Random/IntelliJ IDEA: Coding style and code formatting
Oleksandr Miadelets
Head of Developers Team at CodeGym

IntelliJ IDEA: Coding style and code formatting

Published in the Random group
A programming language is very similar to a spoken language. The only difference is that it is a special language whose main purpose is to facilitate communication with a computer in order to explain to the computer what we want it to do. But you can't have a personal conversation with a computer. When you started learning a programming language, you looked at books or some educational resource like CodeGym. And this resource showed you code that the computer understands. But you too should understand it as you learn about the Java language. As with any language, some formatting conventions have been adopted in programming. For example, in polite society, wRiTiNg LiKe ThIs would be considered bad manners. And in Java, starting a method's name with a capital letter is a gross violation of coding conventions. IntelliJ IDEA: Coding style and code formatting - 1The rules for Java code are given in the document Code Conventions for the Java Programming Language. Coding conventions can also regulate smaller details, such as indentation. Imagine the utter nightmare that version control would become if indentation was inconsistent, some people using tabs and other people using spaces. What would it be like for someone who needs to check in a fix in just one method, but finds the whole file changed due to differences in spaces and tabs? Of course, as with ordinary language, conventions may change depending on where a language is used. For example, in the vast expanses of the web, you can find the Google Java Style Guide and the Twitter Java Style Guide. For this review, we need a test subject. We'll use the Gradle build automation system. It will let us get started quickly by creating a new project from a template. Gradle has a great plugin: Build Init Plugin. Let's go to a new directory and run the following command there: gradle init --type java-application After that, start IntelliJ IDEA. If you see a window with an open project (i.e. you see the code editor and project tree), close this project using File -> Close Project. Now in the welcome window, run "Import Project" and import our new project. When importing, set the "Use autoimport" checkbox. Let's figure out whether we can use state-of-the-art development tools to somehow simplify life.

Code formatting in IDEA

After importing the project, press Ctrl+N and go to the AppTest class. This 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? An annotation on the same line as a method declaration, which looks ugly, right? How to fix this? IntelliJ IDEA has a "Code" menu entry for various code manipulations. One such manipulation is "Reformat Code", which you can apply using Ctrl+L. After you do this, the annotation will be on one line, and the method declaration on another. It's worth noting right away that this operation is performed on the currently selected code. If there is no selection, then the formatting operation is performed on everything. Now let's add a new test method:
public void testSumOfOddNumbers() {
	List<Integer> data = Arrays.asList(1, 4, 2, 3, 6, 7, 9);
	Integer result = -> number % 2 == 0).reduce((n1, n2) -> n1 + n2).get();
	assertThat(result, is(12));
And two imports:

import static;
import static org.junit.Assert.assertThat;
As you can see, the operation on the Stream is on one line. But what if we want to make sure that the chained method calls are always split into new lines at each period operator? We could do this manually. But remember that we want everything to happen automatically. Indeed, we will certainly forget the manual step from time to time, and then we'll end up with different formatting everywhere, and that's no good. So we need to edit the rule that IDEA uses for formatting. Choose File -> Settings in the IDEA menu (or press Ctrl+Alt+S). Enter "Code style" in the search field in the settings window. In the "Code style" section, you can specify settings for more languages than just Java. But Java is what we are interested in right now. As you can see, the settings are divided into several tabs. A super useful feature is that an example of the operation is shown in the right part of the window: IntelliJ IDEA: Coding style and code formatting - 2The screenshot shows that we can set "Chained method calls" to "wrap always", i.e. always split chained method calls into separate lines. Now click the formatting button again in the test class and we see that it really works! But sometimes you need to format some code outside the standard formatting rules. Set up the formatting as follows: IntelliJ IDEA: Coding style and code formatting - 3In order to prevent formatting, in the "Code Style" section, enable formatter markers: IntelliJ IDEA: Coding style and code formatting - 4Now we can change our test class so that its code does not get reformatted:
public void testSumOfOddNumbers() {
	List<Integer> data = Arrays.asList(1, 4, 2, 3, 6, 7, 9);
	// @formatter:off
	Integer result = -> number % 2 == 0)
                             .reduce((n1, n2) -> n1 + n2)
	assertThat(result, is(12));
	// @formatter:on
You may have noticed that when you press Tab, IDEA interprets it as a space (this is the default behavior). But you can change this in the "Code Style" section: IntelliJ IDEA: Coding style and code formatting - 5As you can see, there are a lot of settings there. You can read more details about "Code style" settings here: "IDEA Help: Code Style". There's another important formatting feature: formatting imports. This operation is run separately and is called "Optimize Imports". It is located under Code -> Optimize Imports (Ctrl+Alt+O). Optimizing imports removes unnecessary imports and arranges imports in the correct order according to the settings in the "Imports" tab of the "Code Style" settings for Java. What's more, if you want this formatting to happen automatically, there's good news: this can be accomplished using the Save Actions plugin.

Distributing settings in a command

We saw above that you can customize your formatting style however you please. But how do you use this style within a team? Very easily. There are several options. The simplest is to save a code style scheme. Open IDEA settings using File -> Settings (or press Ctrl+Alt+S). In the "Code Style" section, we can see "Scheme". This is our formatting scheme. By default, the "Default" scheme is used and is labeled "IDE", which means that this setting only applies to our IDE — it doesn't affect anyone else. To make a "custom" scheme, use the button on the right to make a copy and give it a name, for example: CodeGym IntelliJ IDEA: Coding style and code formatting - 6Then that we can import or export the settings: IntelliJ IDEA: Coding style and code formatting - 7 Another option is to import IDEA settings: IntelliJ IDEA: Coding style and code formatting - 8A third option is the Settings Repository. To use the Settings Repository, see the IntelliJ IDEA Help documentation for more details at the following link: Settings Repository". Speaking of pushing a unified style on a team, I also can't help but mention the good support for styles from the Eclipse IDE. To do this, you need to install a separate plugin: open IDEA settings via File -> Settings (Ctrl+Alt+S) and go to the "Plugins" section. To find new plugins, click the "Browse Repositories" button. Then find the Eclipse Code Formatter plugin in the search window. IntelliJ IDEA: Coding style and code formatting - 9After installing it, you'll have to restart IDEA — this is standard procedure. Now everything is done. There is a new section in the IDEA settings: "Eclipse Code Formatter". You can find a sample Eclipse format file here. It will look something like this: IntelliJ IDEA: Coding style and code formatting - 10

Tighter requirements

In addition to IDEA tools, you can also use build automation plugins to tighten requirements. There's no way you could manually check that someone has used proper formatting. Maybe you could with 5 people on a team. But with a 100 people at a company, it's not realistic. And even five will be difficult to track. And why waste your time on any of this? It would be much easier to prevent the project from being built if the rules are violated. In fact, this is a whole separate topic called "Inspect Code". In this article, I just want to show you how it works. One of the most popular Gradle plugins (because it builds our project, you will recall) is pmd. To enable it, just go to our Gradle project's build script (the build.gradle file at the root of our project) and add pmd to 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 enter more detailed settings in the same place:
pmd {
    ignoreFailures = false
    pmdTest.enabled = true
    ruleSets = [
Even our project is broken now. Run gradle build and we get an error. The nice thing is that a report is generated during the build. And if there are errors, we get a message like this:
6 actionable tasks: 6 executed
7 PMD rule violations were found. See the report at: file:///C:/_study/codestyle/build/reports/pmd/main.html
Going to the report, we see something like this: IntelliJ IDEA: Coding style and code formatting - 11Moreover, the "Problem" column provides a link to a description of the problem on the pmd plugin's website. For example, for the "headerCommentRequirement Required" error, the link goes here: pmd — CommentRequired. This error is a hint that our class does not have a JavaDoc. We can use templates to configure a JavaDoc above classes: IntelliJ IDEA: Coding style and code formatting - 12And specify the contents for the File Header: IntelliJ IDEA: Coding style and code formatting - 13After that, we can turn the comment above the App class into a JavaDoc and see that the error is gone in a new build.

The bottom line

Code style is important to maximize productivity on a project. Beautiful code written according to shared rules guarantees that your coworkers will more easily and quickly understand it and won't give you an earful of criticism. With modern development tools, it's not so hard to stick to style rules. I hope this review has proven to you that this is true. Here's a little extra material on the topic:
  • Popular
  • New
  • Old
You must be signed in to leave a comment
This page doesn't have any comments yet