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.
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: Click Next and complete the project initialization setup. Now 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. If 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: Notice 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 . You 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: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 . In 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.
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. In 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 + /
GO TO FULL VERSION