Reformatting code in IntelliJ IDEA
Avatar
Author Lightrun Marketing
Share
Reformatting code in IntelliJ IDEA

The Quick and Easy Guide to Reformatting Code in IntelliJ

Avatar
Lightrun Marketing
28-Jul-2021
8 min read

As a developer, you’re going to be making changes to a codebase. That’s why, as Harold Abelson put it, “Programs must be written for people to read.” If a codebase is not clearly formatted, debugging becomes more difficult than it should be.

Though usually overlooked, little changes like reformatting and proper indentation of your code can obviously differentiate a professional developer’s code base from someone just learning. Keeping your code well-formatted and indented can help you write code that’s easier to read. This makes collaboration on your projects easier and also increases the pace of debugging and other codebase maintenance; it’s easier to troubleshoot code with good readability and structure.

Despite the numerous benefits of properly formatted code, you might still get by as a developer without being disciplined about this, especially given that it can be time consuming. What if you could automate it?

This article will introduce you to a simple method for automatically reformatting your code with IntelliJ IDEA. You’ll learn how to reformat code with IntelliJ, as well as how to exclude part of the codebase from reformatting, using different shortcuts.

The Benefits of Reformatting

It’s important to remember that formatting and commenting code aren’t required for a function to work. Any code, with or without formatting, is entirely capable of being read and executed by a compiler.

Reformatting, on the other hand, makes markup considerably easier to read for humans. The only thing that matters to a compiler is that the code is valid and error-free, not how good or nicely indented it is. But humans are concerned about the latter because they are the ones reading it. Just as with plain text, nobody loves to read shapeless content, without headings, paragraphs, or any sort of indentation.

Some of the necessary reformatting techniques involve:

  • Indentation
  • Style and spelling of functions
  • White space
  • Capitalization and naming
  • Among others!

Debugging is a necessary evil that the average developer will run into frequently throughout their career. But where do you start when your codebase is cluttered and disorganized?

When source code is properly formatted and indented, the code looks less clustered. This makes it easier to determine where the application’s different modules fall, and therefore easier to find issues and errors.

Reformatting code in IntelliJ IDEA is based on the requirements specified in the code style settings on the IDE. Although, when you make use of the EditorConfig in your project, the settings you’ve specified in the .editorconfig file by default override the ones specified in the code style settings anytime you reformat your code.

Reformatting in IntelliJ is not really different than in other IDEs. There are options for reformatting a particular block of code as well as a whole file. There may be times when your whole code block is pretty long and you want everything reformatted, with the exclusion of a few specific areas. In this case, individually selecting the parts of your code you want formatted is definitely not the way to go.

In situations like that, IntelliJ’s reformatting definitely comes in handy. We’ll be exploring that and other use cases as we continue.

Tips for Formatting Code

First, let’s cover a few basic tips for formatting code in general:

  • Ensure your code is properly commented. Use comments to convey intention and meaning. Even if you’re the only one reading your code, this is still helpful for recalling what blocks of your code are intended for, say, if you revisit your codebase after taking a vacation.
  • Do not use tabs for spaces while on the same line. This decreases the readability of your code.
  • Add TODO to your code blocks to help you keep tabs on future implementations. That way, when you reformat your code, it doesn’t give the illusion of your work being finished.
  • Don’t use code reformatting as a quick fix for syntax errors.
  • Avoid deep nesting. This is a common practice among some developers, but deep nesting your code hinders readability and gives room for errors that might not be easily spotted at a glance.

Code Reformatting in IntelliJ

Before we explore the different ways of formatting code in IntelliJ, start by creating a sample Java project in your IDE. Open up IntelliJ—you should see a screen like this:

Java project Intellij

Click Next and finish the project initialization setup.

finish the project initialization setup

Now that your project is set up, it’s time to add some sample code to help you understand code reformatting in IntelliJ. This is a simple word counter from the University of Texas:

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Scanner;
import java.util.TreeMap;

public class SimpleWordCounter {

public static void main(String[] args) {
try {File f = new File("ciaFactBook2008.txt");
Scanner sc;
sc = new Scanner(f);
Map<String, Integer> wordCount = new TreeMap<String, Integer>();
while(sc.hasNext()) {String word = sc.next();
if(!wordCount.containsKey(word))wordCount.put(word, 1);
else wordCount.put(word, wordCount.get(word) + 1);} 

// show results
for(String word : wordCount.keySet()) System.out.println(word + " " + wordCount.get(word));
System.out.println(wordCount.size());
}
catch(IOException e) {System.out.println("Unable to read from file.");
}
}
}

Reformatting Code Fragments

Let’s start by formatting code fragments. To achieve this, simply highlight the portion of code you intend to format and click Code > Reformat Code.

You can see that the highlighted section of your code—in this case, lines 11–17—has been properly formatted.

Let’s take a look at the before and after of our code fragment reformatting.

Before reformatting

After reformatting

If you notice in the first image, the declaration and initialization of your variable happened on the same line as your try declaration. The closing curly brackets are also jumbled up with your else block.

But after highlighting that portion of your code and using the reformatting option, you have a code block that’s pleasing to the eye.

The full code in your class now looks something like this.

Before and after reformatting

Notice that only the block of code you selected got reformatted.

Reformatting Entire Files

To reformat an entire file, open up your editor, place your cursor anywhere, and click Code > Reformat File.

reformat file

You’ll get a prompt asking you to choose relevant reformatting options for the whole file.

This action reformats all your code in the active editor. So your code becomes something like this:

All code in the active editor reformatted

Reformatting a Module or Directory

To achieve this, all you have to do is right-click on the module in the project tool window and select Reformat Code.

reformat module

In the pop-up window, select any of the three options that apply to what you need:

  • Optimize Imports: Choose this if you want to add missing imports statements and also get rid of unused imports.
  • Rearrange Entries: For rearranging your code based on the arrangement rules found in the code style settings.
  • Cleanup Code: For running the code cleanup.

cleanup code

Once you are done, simply click OK.

Exclude Code from Reformatting

Let’s walk through what to do if you have a block of code that you don’t want to include while formatting an entire file.

Go to File > Settings or use the keyboard shortcut Ctrl+Alt+S.

Go to Editor > Code Style and choose the Enable formatter markers in the comments checkbox on the Formatter Control tab.

In your editor, create a line comment and type //@formatter:off without quotes at the beginning of a region that you want to exclude. At the end of the region, create another line comment and type //@formatter:on without quotes.

refactoring exclude

From the image above, you can see that the formatter would ignore your code on line 23, simply because you stated it in the comments and formatter controller.

Examples of Shortcuts for Reformatting

  • Reformat Code Block: Ctrl + Alt + Shift + L
  • Reformat File: Ctrl + Alt + L
  • Add a Line Comment: Ctrl + /
  • Add a Block Comment: Ctrl + Shift + /

Conclusion

Paying attention to your code formats is just as important for a developer as getting it to work in the first place. You never can tell who’ll be visiting your mass of code eventually—having an easy-to-read, well-structured codebase speaks well of a professional developer.

Thanks to IntelliJ, formatting your code does not have to be as difficult as writing the code itself. Next time you’re writing code using IntelliJ, incorporate these tips to help you reformat your code and make it easier on yourself when you need to debug in the future.

Share

It’s Really not that Complicated.

You can actually understand what’s going on inside your live applications.

Try Lightrun’s Playground

Lets Talk!

Looking for more information about Lightrun and debugging?
We’d love to hear from you!
Drop us a line and we’ll get back to you shortly.

By submitting this form, I agree to Lightrun’s Privacy Policy and Terms of Use.