Mar 28, 2011

Eclipse Tip: Fastest Way to Add a New Method

The  Source->Implement Method  menu choice is OK if you've written a bunch of prototypes in your .h file already and want the IDE to create the implementation scaffolding. However, I often want to create a method from scratch. This is, I want to have Eclipse create both the implementation and the definition scaffolding. I accidentally found a good way to do this. While working in a method, I often see a small group of lines that I think can go in a method by themselves so I select them and then select the Refactor->Extract Function refactoring. Presto! I have a new const correct method in both the .cpp and .h file. Perfect.  Sometimes, however I know before I type anything that I need a new method. So what I do is type  int x; one a line. Then I select that line and use the Refactor->Extract Function refactoring and I have my new method. I just delete the int x; line  and start implementing. If I didn't need my new new method where the int x; was highlighted in the original method I can quickly go back and delete that too. Unfortunately, if I need to add parameters I have to do that manually. Still it's a lot better than creating everything by hand.  The next time you need to add a method to an existing class give it  a try. Maybe in the next release of the CDT, the Extract Function refactoring will work with no selection and allows us to specify parameters and we can shave off even a few more keystrokes.

Update:

SNAGHTML1d6850a9One issue I've noticed is that sometimes the extract function refactoring wants to just create a non-member function and just put it above the current function. When the refactoring window open make sure it has the Access modifier: section as shown in the image. If it does then it will create the method as a member of the class and insert the proper code into the include file.   I have yet to figure out why it does this. Even if the selected code contains member variables it will sometimes try to give you a non-member function, which is just going to break your code.  When it shows the Access modifier section I have always had good luck with the resulting code.  I created a bug report that contains a video demonstration on Screenr (there is audio) and more detail for those interested.

Update II: 7/9/2012 – The Extract Function refactoring appears to be fixed in the Eclipse Juno release.

About Me

My photo
Tod Gentille (@todgentille) is now a Curriculum Director for Pluralsight. He's been programming professionally since well before you were born and was a software consultant for most of his career. He's also a father, husband, drummer, and windsurfer. He wants to be a guitar player but he just hasn't got the chops for it.