Recently my friend Piotr posted a question on social media about how to format records in IntelliJ IDEA…
How to format records
Sidenote: I don’t know why he wouldn’t just ask me directly, but I guess this was more fun 😉
Configuring code style
IntelliJ IDEA can format your code for you. Code will be formatted as you type it, and if needed you can Reformat the code (⌘⌥L on macOS) / Ctrl+Alt+L on Windows/Linux). If the (pre)defined code style isn’t to your liking, you can change it.
By default, IntelliJ IDEA will format records with the curly braces {} on two lines. When you apply Reformat to a record, IntelliJ IDEA will let you know “No lines changed: content is already properly formatted”.
Content is already properly formatted
To change the formatting for records so that the curly braces {} will be on the same line, open Settings (⌘, on macOS / Ctrl+Alt+S on Windows/Linux) and go to Editor | Code style | Java. Open the tab Wrapping and Braces and in the section Keep when reformatting select the option Simple classes in one line. Don’t forget to Save Changes.
Settings – Code style
Now if we have any code with a record (or any other simple class), we can use the Reformat the code (⌘⌥L on macOS) / Ctrl+Alt+L on Windows/Linux) to reformat the simple class accordingly. Note that you’ll need to use the shortcut twice to remove custom line breaks.
The same formatting will be applied in other situations. For example, when we add another record to the file, and use Complete Current Statement (⌃⇧⏎ on macOS / Ctrl+Shift+Enter on Windows/Linux), our new record will be completed with the curly braces {} on one line.
What about generating a new Record?
From the Project tool window, we can generate a new record. Use GenerateNew (⌘N on macOS / Alt+Ins on Windows/Linux) and select Java class. In the New Java Class dialog, type the name of your new record, and select Record. Note this record is still generated with the curly braces {} on 2 lines.
To make sure a newly created record is also formatted with the curly braces {} on one line, we can change the File template for Record.
Open Settings (⌘, on macOS / Ctrl+Alt+S on Windows/Linux) and go to Editor | Code style | File and Code Templates. Open the template for Record and change the template to have the curly braces {} on one line. Again, don’t forget to Save Changes.
File and Code Templates – Record
Now when we generate a new record it will be formatted with the curly braces {} on one line.
Note that changing only the File Template for Record is not enough to format records with the curly braces {} on one line. For one, it will be immediately reformatted upon creation according to the code style, as long as the Reformat according to style box is checked for this file template. Even if we uncheck this option, reformatting a file with a record would reformat it to the code style (which by default is {} on 2 lines).
In this blog post, we will look at how to debug Java code using the IntelliJ IDEA debugger. We will look at how to fix a failing test, how to find out where an `Exception` is thrown, and how to find problems with our data. And we will learn some neat tricks about the debugger in the process!
To illustrate using the debugger, we will use a small example application that reads test scores from a CSV file, calculates the average score per student, and prints the results to the console. If you’d like to follow along, you can find the code here.
Debug a failing test
One reason you might need the debugger is when one of your tests fails. In our example application, when we run the tests in `StudentTest`, we see that there is a failing test.
Failing test
Currently, this test fails because the expected average does not match the result of the method `getAverageScore()`, as we can see on line 127. We can use the debugger to find out what the problem is and how to fix it. Let’s navigate to this method so we can set a breakpoint there to see what happens.
Set a breakpoint
We can navigate to the method `getAverageScore()` using Jump to Source (⌘↓ on macOS / F4 on Windows/Linux) when our cursor is on the method. We can place a breakpoint, either by clicking in the gutter or using the shortcut (⌘F8 on macOS / Ctrl+F8 on Windows/Linux). Place the breakpoint on the first line of the method (line 50).
Breakpoint in method
Run in Debug mode
When we run the test in Debug mode (⌃D on macOS / Shift+F9 on Windows/Linux), execution will stop when it hits the breakpoint, so that we can look at the state of our application. We see inline debugging information in the editor.
Run in Debug mode
Here we see that the list of `testScores` has `size = 3`. We can even click in the editor to expand this list to see details of the values in the list. We also see that `testScores.isEmpty()` evaluates to `false`, and therefore the `return` statement inside that `if` statement is unreachable and greyed out.
In the Debug tool window (⌘5 on macOS / Alt+5 on Windows/Linux), we see the call stack (the methods that were called) on the left. We can also see information about objects and variables, like the student and their test scores, in this example.
Debug tool window
Stepping through the application
Now, we can step through the code to see what happens, using different step actions.
Use Step Over (F8) to step over a line and go to the next line, or use Step Into (F7) to step into a method that is called on a line. In this example, we can step into `getTestScore()` – which isn’t very interesting. When we step into a method, we can continue stepping to return to the call site once we exit the method, or use Step Out (Shift F8) to return right away. Notice that the variables and values that are shown inline and in the Debug tool window are updated as we step through the program.
Step through the program
Once all the scores have been added, we see that the` totalScore` is 25. And here, we see the problem with our logic: we forgot to divide by the number of test scores!
Evaluate expression
To fix our problem, we need to divide the total score by the number of test scores. To make sure our intended fix is correct, we can use Evaluate Expression. Right-click on `totalScore` in the editor to open the context menu and select Evaluate Expression. Alternatively, use the shortcut ⌥F8 on macOS / Alt+F8 on Windows/Linux.
Evaluate Expression
If we evaluate `totalScore`, we get 25.0, as we can already see in the debugger. However, we can use Evaluate Expression to evaluate other expressions, even ones not currently part of our code. Here we can try out potential solutions. For example, if we evaluate `totalScore / testScores.size()`, we get “8.333333333333334”, which is the expected average.
Evaluate Expression
Apply fix and rerun tests
Let’s apply our fix to the code to return `totalScore / testScores.size()` instead of `totalScore` from the method `getAverageScore()`. When we rerun the test, we see that it now passes. Note that you might want to run all tests to make sure that your fix has not had any unintended side effects.
Test passed
Since we no longer need the breakpoint, we can remove it, either by clicking the breakpoint in the gutter or by using the shortcut ⌘F8 on macOS / Ctrl+F8 on Windows/Linux.
Run the application
Now that we’ve fixed our failing test and all the tests pass, let’s see if our application works correctly. Go to the `Main` class and run it, for example, by clicking the Run button in the gutter.
Debug an Exception
When we run the application, we see that there seems to be another problem! Our application throws a `DateTimeParseException`, with the message `Text ‘8.7’ could not be parsed at index 0`. Let’s use the debugger to find out what’s wrong.
DateTimeParseException
Note that we can create a breakpoint right from the console, by clicking the link Create breakpoint. This opens the Breakpoints dialog, where an Exception Breakpoint has been added for the `DateTimeParseException`.
Create Exception Breakpoint
Now, when we run our application in Debug mode, execution will stop when and where this exception is thrown, so we can figure out what caused it. Execution stops in the `DateTimeFormatter` class. When we expand the `Exception` in the Debug tool window, we see that the `detailMessage` is “Text “8.7” cannot be parsed as a `DateTime`”. That makes sense, as the number 8.7 does not represent a valid date.
Reset frame
To find out where the incorrect value comes from, we can go back in the call stack. The call stack is shown in the left pane of the Debug tool window. We see a round arrow in front of the last method that was called. When we hover over this arrow, we see the option to Reset Frame.
Reset Frame
We can use Reset Frame to go back to the previous frame. Let’s do so until we get to the point in our code where we try to parse this value into a date. We will need to drop several frames until we get back to our own code. We see that we try to parse a `LocalDate` on line 38 of our `Main` class.
Note that there are limitations to using Reset Frame; it only resets local variables, not static and instance variables. It also won’t undo any side effects of your application, like console output. While this is not relevant in the current example, you should be aware when you use Reset Frame in the future.
We are trying to parse a part of a line from our CSV file. Each line has been split into parts. To see all parts of the current line, click the View link next to the `parts` variable in the Debug tool window. Here we see that “8.7’ is actually a test score, as you might have guessed. We can also see that the line does contain a date, but it is in the next part of the line.
Reset Frame
As we can see in our code, we are parsing the same part of the line (`parts[3]`) twice! This looks like a copy-paste error! We should be parsing the part of the line that contains the date, which is `parts[4]`. Let’s fix that by changing line 38 to `var testDate = LocalDate.parse(parts[4]);`
Note that we could have also gone directly to this line in the code from the console, by clicking the link “Main.java:38” in the console. However, it is useful to know how to set a breakpoint for an exception in case you ever need it.
Go to line in code from console
Print to the console
In fact, while we’re here, let’s make sure that we are parsing all the parts of the lines correctly.
As we can see in the code just above (on line 25), our CSV file contains a header. Let’s print this header to the console to make sure we parse each part of the line to the correct field. We could add a `System.out.println()` to our code to print the header, but we don’t want to risk print statements ending up in production! Fortunately, there is a better way to do so.
Non-suspending logging breakpoint
Let’s create a non-suspending breakpoint, which means that execution will not stop on this breakpoint, and set it to log the line to the console when the breakpoint is hit.
To do so, create a breakpoint on line 27. Right-click the breakpoint and click More to open the Breakpoints dialog. Unselect Suspend to make this a non-suspending breakpoint. Next, select Log and Evaluate & log. Set the Evaluate & log field to `”Header: ” + line` and click Done. Notice that the breakpoint is yellow, to signify that this is a non-suspending breakpoint.
Non-suspending breakpoint
Now, when we run the application in Debug mode, we see that the header is printed to the console. But so are all the other lines from the file. To print only the header, the breakpoint should be on the next line. We could set a new breakpoint there, but then we’d have to redo the configuration…
Drag and drop breakpoint
Instead of creating a new breakpoint, we can drag and drop the existing breakpoint to the next line, preserving its configuration.
Drag and drop breakpoint
Now, when we run the application in Debug mode, only the header is printed to the console. Along with the output of our program, of course. It looks like our fields correspond correctly to the headers of the file.
Checking the functionality of the application
Let’s run our application again to see if everything is now as it should be. We see that the application runs without errors, but it looks like one of the students has a negative average test score.
Negative average score
That can’t be right! Let’s see what’s going on. We’ll set a breakpoint in the code where we add test scores to the student (line 45 in `Main.java`). When we run our application in Debug mode, execution will stop every time this breakpoint is hit. We can click the Resume Program button (⌥⌘R on macOS / F9 on Windows/Linux), either in the Debug tool window, or inline in the editor, to get to the next test score.
Resume program
Every time we click the Resume Program button, we can see the values change both in the inline debugging information in the editor and in the Debug tool window. Execution will stop every time it hits this breakpoint, so for every test score. Since there are a lot of test scores in the file, this is going to take a while…
Resume program
Conditional breakpoint
As we are only interested in the test scores for a particular student, we don’t need execution to stop for each test score. Instead of clicking the Resume Program button many times in a row to get to the scores we’re interested in, we can use a conditional breakpoint – which will only halt execution under certain conditions.
Right-click the breakpoint to open the Line Breakpoint dialog and edit the configuration for the breakpoint. Since we don’t need execution to suspend until we process this particular student’s test scores, we can set the field Condition to `studentName.equals(“Olivia Garcia”)` and click Done.
Conditional breakpoint
Notice that the breakpoint has a small question mark in it, to signify that it is a conditional breakpoint. Now, when we resume our program, execution will stop only once we get to the test scores for the student whose name we have set in the condition. Here we can see that the test score is negative.
Negative test score
Add watch
To see whether all test scores for this student are negative, let’s add a watch to the field `testScore`. Adding a watch makes it easier to explicitly watch the value of a field. Right-click on the variable `testScore` in the Threads & Variables tab in the Debug tool window and select Add to watches from the context menu. The watch will be shown in the right pane of the Debug tool window.
Add to Watches
If needed, select the Layout Settings icon at the top right of the Debug tool window and select Watches in the list, to show watches in the right pane.
Add Watches to Debug tool window
When we click Resume Program and loop over this student’s scores, we see that all her scores are negative. That would explain her negative average…
This looks like a problem with the input data. Let’s open the CSV file to correct the scores and make sure Olivia’s scores are no longer negative. We can use multiple carets to fix all scores at the same time.
In this example, we can fix our input data ourselves. If you are dealing with user input that you can’t change, consider adding validation to the code, for example, that test scores cannot be negative.
Final check
Let’s run our application one more time to see that everything is in order. We see that average scores are printed to the console for all students, and none of the scores are negative. This is how our application is expected to work.
Final check
Conclusion
In this blog post, we’ve seen how to use the debugger to find and fix several types of bugs, from problems with the logic in the code, to reasons that exceptions are thrown, and finding problems with input data.
Is there anything else you’d like to learn about the debugger? Please tell us in the comments!
This article was first published in NLJUG‘s Java Magazine. You can view an online copy here.
As developers, we read code more than we write it. Research has shown that “developers on average spend as much as 58% of their time comprehending existing source code” (The Programmer’s Brain – Felienne Hermans). And yet, we don’t practice reading code nearly as much as we do writing code. Let’s look at how to practice reading code and how IntelliJ IDEA can help.
Code Reading Club
In 2022, a friend invited me to join a Code Reading Club, based on the work of Felienne Hermans. We have monthly sessions where we take a sample of code and apply structured exercises to this code to try and make sense of it. I have really enjoyed our sessions, not only for the opportunity to practice reading code, but also because I find it very interesting to learn how other people read code. To start your own club, use the Code Reading Club resources. Or try the code reading exercises from Felienne’s book, The Programmer’s Brain.
While it’s possible to use these exercises in our daily work, developers mostly read code in the IDE.
Exploring an existing code base
When joining a new team or company, you need to quickly get up to speed with existing code bases. Obviously you can look at the project, but unfortunately not everything can be captured in the code.
It helps to have a teammate give an introduction to the application; a description of what the application does, its place in the landscape, relevant history and design choices, current plans (are you actively developing new features or mostly doing maintenance?), which parts of the application are changed more than others, as well as links to existing documentation and other relevant information. Also think about which stories a new team member can pick up to help them become familiar with the project.
As a new team member, check out all relevant repositories. Make sure you can build the project, run the tests and run the application locally. How to do this will hopefully be described in the README. If not, consider adding it. Running the project locally can help you to both see how the application works by trying it out, and make sure that you can test your changes when you are done.
Opening a project in the IDE allows you to search and navigate your codebase more easily, as well as use additional useful IDE features. Let’s dive into several powerful IntelliJ IDEA features you can use to quickly be productive.
Note: Keyboard shortcuts are provided for macOS and Windows/Linux respectively.
Project overview
Explore modules and packages in the Project tool window (⌘1 | Alt+1) to get an idea of the project. If you prefer a visual representation, IntelliJ IDEA can generate several types of diagrams for you, including UML class diagrams. Also consider drawing your own diagrams; this will help you retain the information better and lets you focus only on the information you need for the task at hand.
To understand dependencies between modules, packages and classes, the Dependency Structure Matrix (DSM) can help. Open the DSM from the main menu using Code | Analyze Code | Dependency Matrix….
Dependency Structure Matrix
In this example the matrix displays modules in a project. As you can see in the legend at the top right, dependencies are marked in blue and the direction of the dependencies is marked in green and yellow; the module marked in green depends on the module marked in yellow. Visualising the dependencies can help us to get an overview of the application. If you prefer, you can also generate a Project Modules diagram. Note that this diagram only gives you one side of the equation (which modules the selected module depends on).
Search & navigate
Use Search Everywhere (⇧⇧ | Shift+Shift) to find anything in your project, including IDE settings & features. Other useful navigation features include Recent Files (⌘E | Ctrl+E) or Recent Locations (⌘⇧E | Ctrl+Shift+E). Knowing how to search and navigate code in your IDE is helpful when working with existing code, so you can focus on the task at hand.
Looking at a slice of the application
Instead of looking at the whole code base, look at a specific slice of the application. For example, find the main method and see what the application does from there, find a specific endpoint and trace the code down to the database, or find the location where an error is thrown and trace the code back up to how you got there.
Understanding a piece of code
At some point you’ll find a piece of code that you will need to understand, for example, to fix a bug or make necessary changes. If you’ve ever been overwhelmed by a piece of code without any idea how to start, this is where code reading exercises can help! Of course, your IDE can also provide you with handy features. For starters, IntelliJ IDEA provides you with hints about the code, like syntax highlighting, inlay hints and gutter icons.
One of the reasons code can be confusing is because of a lack of information. For example, you might not know the exact implementation of a class or method. While you can Jump to Source (⌘↓ | F4) to navigate to the relevant code, and use shortcuts to Navigate Back (⌘[ | Ctrl+Alt+Left Arrow) and Navigate Forward (⌘] | Ctrl+Alt+Right Arrow), it’s easy to get lost in a large code base. To see where a particular file is located in the project, use the crosshair icon at the top of the Project tool window.
Select Opened File
It is also possible to pull up additional information using Quick Documentation (F1 | Ctrl+Q) to show the Javadoc, Quick Definition (⌥␣ | Ctrl+Shift+I) to see the code or Type Information (⌃⇧P | Ctrl+Shift+P) to determine which type is returned by an expression.
Did you know IntelliJ IDEA can help you work with regular expressions? You can mark a String as RegExp from Show Context Actions (⌥⏎ | Alt+Enter), using Inject Language or Reference and selecting RegExp (or a specific flavor of regular expressions). From the Show Context Action menu, select Check RegExp to open a popup where you can check whether a certain String matches the regular expression. Place your String in the Sample field in the popup; a yellow warning sign will be shown if the String is incomplete, a red exclamation mark shows the String does not match, or a green check mark will indicate that the String matches the RegExp.
Check RegExp
The structure of the code
Code is not read from top to bottom. Code doesn’t run linearly either! Developers “scan” code looking for the parts you’re interested in. Using white space and formatting can help improve readability.
When you write code in IntelliJ IDEA, the code will be formatted automatically. If you encounter code that isn’t properly formatted, you can reformat it (⌘⌥L | Ctrl+Alt+L).
You can collapse the code (⌘⇧- | Ctrl+Shift+Minus) to get an overview of a class without being overwhelmed with too many details. You can expand it again (⌘⇧+ | Ctrl+Shift+Plus) as needed. Other ways to get a quick overview of the code are to use the File Structure popup (⌘F12 | Ctrl+F12), or the Structure tool window (⌘7 | Alt+7).
When reading code, it might help to play with it a little bit as you try to understand it. Remember to revert any changes you make!
Restructure
Restructure the code by moving code blocks around to match your mental model, preferred style or coding conventions. Use shortcuts to move a statement up (⌘⇧↑ | Ctrl+Shift+Up Arrow) or down (⌘⇧↓ | Ctrl+Shift+Down Arrow).
Refactoring
You can use refactoring to change the code to aid your understanding. Rename variables or methods (⇧F6 | Shift+F6), extract variables (⌥⌘V | Ctrl+Alt+V) or extract methods (⌥⌘M | Ctrl+Alt+M) and give them meaningful names, inline variables (⌥⌘N | Ctrl+Alt+N) you don’t need. The most frequently used refactorings are available in the Refactor This menu (^T | Ctrl+Alt+Shift+T) . Additional refactorings or quick fixes might be available under Show Context Actions (⌥⏎ | Alt+Enter).
Testing
Look at the tests for a piece of code to see what this code is supposed to do, using Navigate to Tests (⌘⇧T | Ctrl+Shift+T). Hopefully names of the tests will express the intended behavior of the application. This is useful for two reasons: 1. The tests will serve as executable documentation of the system. 2. Should the tests fail in the future, good names can help to quickly tell you what’s wrong, so you don’t spend more time than necessary analyzing failures.
Debugging
Run code through the debugger to see if the actual behavior of the code matches your understanding. Place a breakpoint (⌘F8 | Ctrl+F8) in the code at the point where you want to observe its state. Run the test in debug mode (⌃D | Shift+F9); execution will halt when it hits the breakpoint. You can observe the state of objects & variables in the editor and in the debug window, and look at the call stack in the Debug tool window. Continue execution by either stepping into a method (F7) or stepping over a line (F8).
The IntelliJ IDEA debugger is very powerful and has many useful features. I highly recommend familiarizing yourself with its features; this will come in handy next time you need to urgently debug your code for a production incident!
Version control
Sometimes you might want to know how the code came to be the way it is, and do a bit of what I like to call “Git archeology”. Use Annotate with Git Blame to see when the code was last changed. Click the commit in the gutter to navigate to that commit in the Git tool window and look at the diff. If you’re using JetBrains AI Assistant [13], you can also ask it to explain the commit to you. Right-click the commit and select Explain Commit with AI Assistant from the context menu.
Explain Commit with AI Assistant
AI Assistant features to understand code
Finally, AI coding assistants, like JetBrains AI Assistant, may offer other useful features for understanding existing code. For example, chat with an AI Assistant and ask questions about software development, your project’s code and version control. Ask it to explain specific code to you, maybe even explain regular expressions, SQL queries, cron expressions, etc.
Because it is deeply integrated within IntelliJ IDEA, JetBrains AI Assistant can explain runtime errors right from the console. With another assistant you may need to copy-paste the error into a chat window. Alternatively, use an AI assistant to write documentation for a class or method. The generated Javadoc is often more concise than the explanation in the chat.
Conclusion
I hope you found this overview useful to see how to approach understanding existing code with the help of IntelliJ IDEA. This article is based on my talk “Reading Code”, which includes live demos of the features discussed in this article.
Discover 7 powerful ways to supercharge your version control with JetBrains AI Assistant!
From resolving tricky merge conflicts to generating precise commit messages, AI Assistant offers tools that can save you time and boost your productivity. Learn how to ask questions about your project’s version control history, review local changes, and even customize commit prompts to fit your style. Whether you’re dealing with complex git commands or want help revisiting old commits, JetBrains AI Assistant has you covered.
Watch now to explore how you can transform your version control experience!
Struggling to understand complex code? JetBrains AI Assistant is here to help!
In this video, we walk you through practical examples of how the AI Assistant simplifies code comprehension. From summarizing projects and explaining classes to clarifying regex and runtime errors, this tool enhances your productivity and understanding. You’ll also learn how to use natural language queries, write concise documentation, and even dig into commit history with ease.
Whether you’re dealing with unfamiliar code or just need quick insights, JetBrains AI Assistant has you covered!
As developers, we spend more time reading code than writing it, and this video provides tips to enhance your code-reading skills within the IntelliJ IDEA IDE. Learn how to leverage features like syntax highlighting, inlay hints, and code formatting to navigate and understand code effortlessly. Discover techniques to quickly scan code, collapse and expand sections for efficient navigation, and use powerful search functionalities to locate specific elements.
Whether you’re a beginner or an experienced developer, these tips will empower you to read and comprehend code with confidence, making your coding journey in IntelliJ IDEA a seamless and productive experience.
While working on a new feature, you find some small other things to fix. Since these changes are unrelated, you probably shouldn’t commit them together. You could revert these changes to redo them separately, but who wants to do extra work? Fortunately, you can now select which chunks or even lines of changes to add to your commit. You can commit the rest separately or even move it to a new change list.
When working with large, complex software projects, we need to understand the dependencies between components in your projects.
IntelliJ IDEA’s Dependency Structure Matrix (DSM), or Dependency Matrix, that can help us with this! Let’s take a look at how to use the Dependency Structure Matrix to see dependencies between different components, like modules, packages, and classes. See how to identify dependencies, find cyclic or mutual dependencies, and visualize the flow of dependencies to see which components use or depend on other components and vice versa.
IntelliJ IDEA is designed to help developers like us stay in the flow while we’re working. Like all IDEs, it has a lot of functionality available, but it’s designed to get out of your way to let you focus on the code.
Take a look at this overview of IntelliJ IDEA.
Introduction
Find Action: ⌘ ⇧ A (on macOS) / Ctrl+Shift+A (on Windows/Linux)