February 3, 2008

Effective Eclipse IV: Fix it, quickly

You are in trouble. Red lines are everywhere. There is no easy way out, so you just either start googling what went wrong, or start a copy&pasting session. If it is so smart, it can tell me that I have an error in my code, why cannot it just fix it?

Well, let me introduce you a powerful ally: Quick Fix.

A small example

On the image above is a well-known situation. The method is throwing a checked exception, so the calling method must either enclose it in a try-catch block, or rethrow it. A typical solution to this problem is to manually write the try-catch block or throws clause. But there is a better way, the way of quick fix.

It can be invoked in two ways

  • clicking on the bulb, left of the line number
  • hitting CTRL + 1 - the preffered way
The result will be..

..that quick fix will propose you both fixes. In the yellow box is a preview, it looks messy, but the code will be properly formatted. If you don't like the generated code, you can change it under Window->Preferences->Java->Code Style->Code Templates. I don't like the default e.printStackTrace(), so I changed the Catch block body template to
logger.severe("Exception caught: " + ${exception_var});
Whenever a red line appears, quick fix can eliminate it. It is applicable not only to the situation above, it can fix:
  • Typos
  • Imports
  • Casting

    Starting with the simple casts...

    .. to even more intricate

  • and any other kind of problem I am unable to think up at the moment.
I found quick fix helpful even in the desperate situations like this one:

Project needs to migrate WTP metadata? Ok then, have your fun.

When there is nothing to fix, quick fix turns itself to a quick refactoring. Let's see what will it propose on our list.

See, it provides all sorts of context sensitive advices. Refactoring, renaming, annotations, everything is there, hidden under one shortcut key. A powerful shortcut key, definitely.


James said...

That's a really good post, which would go very well up on EclipseZone (eclipse.dzone.com). I'm a zone leader there, and would be delighted to have this series up there.

Let me know if you're interested.

Tomáš Kramár said...

Of course, this is simply an offer I cannot refuse. Please, contact me via email (in my profile) so we can discuss the details.