DEV Community

Mark Rubin
Mark Rubin

Posted on • Updated on

Use Your IDE's Code Formatter

This is part of a brief series on Good Habits For Java Programmers.

Consistently and well formatted code makes a huge difference to code readability. If the indentation varies, if opening and closing curly braces don't match up, if how many blank lines you use in between methods varies, the code gets harder to read. Your IDE will come with some way to tell it to automatically format your code for you. Use that to get many of these formatting problems fixed for free!

Which formatting options should I choose?

The autoformatter of your IDE will be opinionated. Your IDE will have it configured with a bunch of standard preferences the author thought were best. You can change these if you like, but don't worry about it: if you're into it (e.g. you really wish it used 5 spaces instead of 4 for indentation), go ahead and make changes; but the defaults are going to be very good for what you're doing as a beginning programmer. The important thing is that the formatter is rules based and will be consistent, saving you from having to decide what formatting conventions you want to obey and most importantly, from having to detect violations and fix them manually. You're unlikely to win that game, and who wants to play it anyway?

Autoformatting won't fix everything

Some formatters cover more conventions than others, and there are settings you can tweak, but, for example, your formatter often won't catch extra newlines or inconsistencies in how you use them:

        if (isValid) {
            System.out.println("The input is valid");
        } else {
            System.out.println("The input is not valid");
            System.out.println("Please enter another value");

            System.out.println("Thank you");


        }
Enter fullscreen mode Exit fullscreen mode

There's an inconsistent, extra newline there before System.out.println("Thank you"); that your formatter probably won't catch. And there are extra newlines after that statement that your formatter likely won't remove. So you still want to do some grooming of your own, but the formatter goes a long way. A really long way.

So how do I do it?

  • Eclipse Ctrl+⇧+F on Windows/Linux; ⌘+Shift+F on Mac
  • IntelliJ Ctrl+Alt+L on Windows/Linux; ⌘+⌥+L on Mac
  • Visual Studio Code It takes some configuration.

There's a lot to explore here if you like, including formatting only a block of code, invoking the formatting commands from a menu option, removing unneeded imports, etc. Have fun further exploring your options!

Top comments (0)