Extract Method: My favourite eclipse shortcut

This is without a doubt my favourite and most useful shortcut in eclipse - extract method.


ALT + SHIFT + M - Extract Method

I like my code to be readable. I like understanding what's going on in a piece of code without going through hundreds of lines and trying to figure out what's going on, because I like working quickly. When I write code, I usually end up going against this, and putting in chunks of code that would benefit from being standalone methods, so, using this shortcut, I can choose some statements in my code and put them into a separate method, and very easily tidy up my code and make it look much neater for the next person that has to deal with it. 

Imagine the following two methods:




So here, I have some duplicate code, and some very simple methods that look a bit too complicated for what they are. I'd have to read every if test to understand what each method does semantically, and I've copied the password checks twice. Bad Coder! So firstly, I'm going to deal with the duplication, by selecting the two if tests for the password validations:


And then pressing ALT + SHIFT + M , I am presented with the following dialogue box:


Here I can choose a few things that I want my new method to do, but usually the most you'll need to do is choose an appropriate name. Notice the 'Replace 1 additional occurrence of statements with method' part. That number changes according to how many duplicate instances of the selected code appears in the class. Once I click OK, I am presented with a wonderful new method:



and the original pieces of code that used the selected statements have been refactored to use the new method:


This all took the best part of 10 seconds to do, and I find it an incredibly easy way of quickly cleaning up code once you're done with it (or even during development). Using the shortcut a couple more times in this class, I can end up with some much more pleasant looking methods:


Now I don't need to trawl through endless if statements to understand what's going on. I can quite easily see that initial validation will validate account Id and password, and secondary validation will validate username and password. If I need to modify password validation, I now only need to change it in once place, and it's much easier to modify the rest of the code if necessary. Need a new piece of validation? Just throw in another method! There are times when the new method isn't exactly what you need, but then it's easy enough to modify it!

I find myself using this shortcut on a daily basis, and I'm usually moaning at people to use it to clean up their code, and they usually love it. So remember, ALT + SHIFT + M , to extract statements to a new method in eclipse!

Happy Refactoring!



Comments