This article is about a relatively unknown feature of Intellij-IDEA called Show Call Hierarchy. Most people who use Intellij-IDEA already know about the Find Usages command, but Call Hierarchy is like that command on steroids.
Here’s how it works. Imagine you’ve got this giant and/or convoluted code base and you want to know what parts of the code are calling a certain method. Find Usages will do that for you, but what if you also want to see who is calling the methods that are calling the method? Call Hierarchy gives you that information.
As a scenario, let’s say we’ve got a class named Root that calls methods named edge1 and edge2 . Both of these call a method named endpoint . Here’s how that class looks:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
package mavensnapshot; public class Root { public static void main(String[] args) { new Root().run(); } public void run() { edge1(); edge2(); } private void edge1() { endpoint(); } private void edge2() { endpoint(); } public void endpoint() { } } |
Use your imagination and pretend that this code is spread between many classes so it’s not so easy to follow. Now you want to know who is calling the endpoint method. If you put your cursor on the endpoint method name and then run Navigate -> Call Hierarchy from the menu, this is what you will see:
This conveniently shows you that endpoint is called by edge1 and edge2 . By double clicking on any of these method names, it will place your cursor on the code. And the great thing is that if you want to figure out who calls the callers, you can expand the tree. In this case, it will look like this:
Now imagine you have some tests calling endpoint . This test code will be shown in a different color so you can easily differentiate between test code and production code that calls your method.
If the tests are getting in your way, you can choose what you see by changing the “Scope” dropdown. Here are the options:
This feature is really useful in getting a bigger picture of the code you’re looking at. It can often help you with refactoring. For example, you may notice that a method is being called by a test but no production code so it should be deleted. You may think you can remove a method parameter but then realize that another method you didn’t expect calls it and that makes you revise how much time a refactoring would really take. If Call Hierarchy isn’t already a part of your Intellij-IDEA tool-belt, you should start using it as soon as possible.