Refactoring

Code refactoring can be a real pain. As your project grows, adding a parameter to a method or renaming it can turn into a nightmare. Eclipse has some refactoring tools that make such tasks a walk in the park.

Renaming variables

Renaming variables manually can be tedious and time consuming. You could resort to find/replace to make it a little less painful. But since the variable name might be matched in other places of the code, you have to go through each match of the variable name and verify if it has to be modified (try renaming a variable named x in a big enough class and you'll understand). If the variable is public, you would also have to scan the whole project for references of this variable.

Luckily, Eclipse does this for you. Just right-click on any occurrence of the variable in the code and navigate to Refactor | Rename. Type the new variable's name and hit Enter.

You can see that even if the name's variable occurs in other parts of the code, only the text that's within the variable's name is modified. Eclipse is only able to do that because it compiles the code and uses information from this process to know which ones are references of the variable in the code. Because it relies on the compiled code, it's not possible to rename a variable inside a class with compiling errors. Eclipse also won't allow you to change a variable's name to one that already exists in the same context. Renaming also works with other elements, such as classes, methods, and interfaces.

Note

Don't let Eclipse's features soften you! Just because it's super easy to rename a variable, you shouldn't feel free to ignore good code practice, such as variable encapsulation. Good code is good code, regardless of the IDE.

Modifying a method's signature

Modifying a method's signature poses similar inconveniences for renaming variables. Eclipse can also help in that task. Right-click on the method's name, and navigate to Refactor | Change Method's Signature. You will be presented with a window that allows you to change the method's access modifier, return type, method name, and add/remove parameters.

On modifying a method's signature, all calls to that method are also modified. When you add a new parameter to the signature, you can choose a default value that will be added to the calls.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset