Saturday 31 December 2011

How to Refactoring in Eclipse for Selenium automation


8. Refactoring

Refactoring is the process of restructuring the code without changing his behavior. For example renaming a Java class or method is a refactoring activity.
Eclipse supports simple refactoring activities, for example renaming or moving. For example you can select your class, right click on it and select Refactor → Rename to rename your class or method. Eclipse will make sure that all calls in your Workspace to your your class or method will also be renamed.
The following shows a screenshot for calling the "Rename" refactoring on a class.
Renaming a class
For the next examples change the code of "MyFirstClass.java" to the following.
   
package de.vogella.eclipse.ide.first;

public class MyFirstClass {

public static void main(String[] args) {
System.out.println("Hello Eclipse!");
int sum = 0;
for (int i = 0; i <= 100; i++) {
sum += i;
}
System.out.println(sum);
}
}

Another useful refactoring is to mark code and create a method from the selected code. For this mark the coding of the "for" loop, right click and select Refactoring → Extract Method. Use "calculateSum" as name of the new method.
Extract Method refactoring
The resulting class should look like the following.
   
package de.vogella.eclipse.ide.first;

public class MyFirstClass {

public static void main(String[] args) {
System.out.println("Hello Eclipse!");
int sum = 0;
sum = calculateSum(sum);
System.out.println(sum);
}

private static int calculateSum(int sum) {
for (int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}

You can also extract strings and create constants from them. Mark for this example "Hello Eclipse!", right click on it and select Refactor → Extract Constant. Name your new constant "HELLO".
Extract Constants
The resulting class should look like the following.
   
package de.vogella.eclipse.ide.first;

public class MyFirstClass {

private static final String HELLO = "Hello Eclipse!";

public static void main(String[] args) {
System.out.println(HELLO);
int sum = 0;
sum = calculateSum(sum);
System.out.println(sum);
}

private static int calculateSum(int sum) {
for (int i = 0; i <= 100; i++) {
sum += i;
}
return sum;
}
}

Eclipse has much more refactorings, in most cases you should get an idea of the performed action by the naming of the refactoring operation.