JavaRush /Java Blog /Random EN /Coffee break #86. A Quick and Easy Guide to Reformatting ...

Coffee break #86. A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA

Published in the Random EN group
Source: Lightrun As a developer, you will have to make changes to the codebase. And if the code base is not clearly formatted, then debugging will become much more difficult for you. Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 1Small changes like reformatting and proper indentation in code are usually overlooked, but they obviously help differentiate a professional developer's codebase from a beginner's codebase. Maintaining proper code formatting and indentation will help you write code that is easier to read. This simplifies collaboration on projects, increases the speed of debugging and maintaining the code base. The code becomes more readable and structured. Is it possible to speed up the code reformatting process? This article will introduce you to a simple method for automatically reformatting code using IntelliJ IDEA. You'll learn how to reduce the time required for this procedure, and you'll also learn how to exclude parts of the codebase from reformatting using various keyboard shortcuts.

Benefits of reformatting

It's important to remember that no formatting or commenting code is required for the function to work. Any code, with or without formatting, can be fully read and executed by the compiler. On the other hand, reformatting makes the markup much easier for people to read. For the compiler, all that matters is that the code works and that it does not contain errors, and not how good it is or how nicely indented it is. True, it is the latter that worries people, because they have to read such code. Just like with plain text, no one likes to read formless content without headings, paragraphs, or any indentation. Some of the necessary reformatting techniques include:
  • Indent.
  • Style and writing functions.
  • Empty space.
  • Use of capital letters and names.
Debugging is a necessary evil that a developer will encounter frequently throughout their career. Where to start if your codebase is cluttered and disorganized? When source code is properly formatted and indented, it appears less clustered. This makes it easier to determine where the different application modules are located. Consequently, it becomes easier to find problems and errors. Code reformatting in IntelliJ IDEA is based on the requirements specified in the code style settings in the IDE. Although, when you use EditorConfig in your project, the settings you specify in the .editorconfig file will by default override those specified in the code style settings. Reformatting in IntelliJ is no different from working in other IDEs. There are options for reformatting both a single block of code and the entire file. There may be times when your entire block of code is quite long and you want everything to be reformatted except for a few specific areas. In this case, individually choosing the parts of the code that you want to format is definitely not the best option. In such situations, reformatting with IntelliJ will definitely come in handy. We'll explore this and other uses of the IDE.

Tips for formatting code

Let's look at some basic tips for formatting code in general:
  • Make sure your code is properly commented. Use comments to convey intent and meaning. Even if you are the only one reading this code, it is still useful to remind yourself of the purpose of certain blocks of code. This will make things easier if you return to your codebase after a vacation, for example.

  • Don't use tabs for spaces on the same line. This reduces the readability of the code.

  • Add a TODO to your code blocks to keep track of future implementations. This way, when you reformat your code, it won't create the illusion that your work is complete.

  • Don't use code reformatting as a quick fix for syntax errors.

  • Avoid deep investments. This is a common practice among some developers, but deeply nested code makes it difficult to read and introduces errors that are not easy to spot at first glance.

Reformatting code in IntelliJ IDEA

Before we explore different ways to format code in IntelliJ, start by creating a sample Java project in your IDE. Once you launch IntelliJ, you should see a screen like this: Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 2Click Next and complete the project initialization setup. Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 3Now that your project is set up, it's time to add 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);
            // sc.useDelimiter("[^a-zA-Z']+");
            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 snippets

Let's start by formatting the code snippets. To do this, simply highlight the part of the code you want to format and click Code > Reformat Code . As you can see, the highlighted portion of your code (in this case lines 11-17) is formatted correctly. Let's look at the “before” and “after” of reformatting our code snippet. Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 4Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 5If you noticed in the first image, the declaration and initialization of your variable happened on the same line as try . The closing curly braces are mixed in with the else block . But after highlighting this part of your code and using the reformatting option, you'll end up with a block of code that's more pleasing to the eye. The complete code for your class now looks something like this: Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 6Notice that only the code block you selected has been reformatted.

Reformatting entire files

To reformat the entire file, open the editor, place the cursor anywhere and click Code >Reformat File . Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 7You will be prompted to select the appropriate reformatting options for the entire file. This action will reformat all your code in the active editor. Your code will become something like this: Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 8

Reformatting a module or directory

To do this, all you need to do is right-click the module in the project tools window and select Reformat Code . Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 9In the pop-up window, select any of the three options you need:
  • Optimize Imports : Select this option if you want to add missing import statements and also get rid of unused imports.

  • Rearrange Entries : To reorganize the code according to the layout rules specified in the code style settings.

  • Cleanup code : to run code cleanup.

Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 10When you're done, just click OK.

Excluding code from reformatting

Let's look at what to do if you have a block of code that you don't want to include when formatting the entire file. Go to File > Settings or use the keyboard shortcut Ctrl + Alt + S. Go to Editor > Code Style and check Enable formatter markers in the comments menu on the Formatter Control tab . In your editor, create a line comment and type //@formatter:off without quotes at the beginning of the area you want to exclude. At the end of the area, create another line comment and enter //@formatter:on , also without quotes. Coffee break #86.  A Quick and Easy Guide to Reformatting Code in IntelliJ IDEA - 11In the image above, you can see that the formatter will ignore your code on line 23 simply because you specified it in the comments and format controller.

Examples of hotkeys for reformatting

  • Reformat code block: Ctrl + Alt + Shift + L
  • Reformat file: Ctrl + Alt + L
  • Add a comment to the line: Ctrl + /
  • Add block comment: Ctrl + Shift + /

Conclusion

Paying attention to code formats is just as important for a developer as making it work. You can never tell who will end up working on your code. Having an easy to read, well-structured code base speaks of a professional developer. With IntelliJ IDEA, formatting your code doesn't have to be as difficult as writing the code itself. Next time you write code using IntelliJ, use these tips. This will make your life easier when debugging your code.
Comments
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION