48

I'm currently working on a legacy java code which was written with almost no coding conventions or common practices. I often come across working but very lousy code snippets (typos in variable names, redundancy and many others) that I find myself urging to fix. In one of those instances, I've found a class that contains three methods with different names but almost identical method bodies.

As per my initial observation, the only difference was the name of one of the parameters.

Before taking any steps and merge them though, I wanted to make a comparison of three methods to see if there's any subtle difference that I didn't notice.

I know it's possible to compare two files, compare with the version from VCS etc. but I was not able to find a quick way to compare the method definitions in the same file.

Is there a more practical way to compare different sections of the same file in IntelliJ rather than copying them into different files and run a file comparison?

Thanks,

Mustafa
  • 2,447
  • 23
  • 31

2 Answers2

121

Another quick way to compare methods (or any block of code) within IntelliJ:

  1. Copy one version to the clipboard.
  2. Highlight the other version.
  3. Use the "Compare with Clipboard" feature from either the context menu in the editor or from View > Compare with Clipboard.
Kristen Balhoff
  • 1,211
  • 1
  • 8
  • 2
  • I appreciated this answer very much, but I couldn't find a way to have the cursor jump between the two windows in the compare view. Instead, I have used "split" to split the active editor in two, either horizontally or vertically, and then use the control+tab switcher, to jump the cursor between the two. – Bram Luyten Dec 01 '18 at 14:58
  • Currently this non-accepted answer is 12.875 more times popular than the accepted one XD Really was helpful for me, thanks – Scott Anderson Mar 30 '21 at 09:54
9

IntelliJ has Locate Duplicates in the Analysis. It's highly configurable and language-aware to the point that it's not just looking for blocks of text that are the same. It would be able to detect if two blocks of code are the same, but with different variable names for example.

You can even expand the scope so that it detects code duplicates that in different files.

See this help page for more information.

dbrown0708
  • 4,544
  • 4
  • 25
  • 22
  • 5
    Worth noting that this is only available in the paid "ultimate edition" not the open-source "community edition". (Not that it's overly expensive - it's a great tool - It just took me a while to work out why I was missing it....) – Michael Anderson Jan 13 '15 at 12:55