31 Mart 2009 Salı

Intellij Knows How To "Extract Method"

Intellij has a great refactoring feature called "Extract Method". You can convert a code piece into a method using this feature. In this process, Intellij can handle all method parameters and return values. You can use this feature first by selecting the code piece you wish to convert to method, and press CTRL+ALT+M.

I will explain what impressed me most about this feature using following example. In the following code, I am not comfortable with the first try/catch block and I want to hide this dirty code inside a method.
 1     public static void main(String[] args) {
2 Connection conn = null;
3
4
//I am not comfortable with following try/catch block
5 try {
6 Class.forName("com.mysql.jdbc.Driver");
7 } catch (ClassNotFoundException e) {
8 e.printStackTrace();
9 System.out.println("Driver not found");
10 return;
11 }
12
13
try {
14 conn = DriverManager.getConnection(
15 "jdbc:mysql://localhost/petshop", "root", "changeme");
16 Statement statement = conn.createStatement();
17 } catch (SQLException e) {
18 e.printStackTrace();
19 }
20 }
21
To achieve this, position the cursor over 5th line and press CTRL+W. By the way, this is another nice Intellij feature called "Incremental Select" :).



Then, press CTRL+ALT+M. Notice that, the return type of the method is boolean. Click OK and see what we'll get:


Following is the refactored version of our code. Let's see what happened. Intellij put the code inside a method which returns boolean and wrapped the method call inside an if statement. This was the only possible solution which wouldn't violate the flow of program:).

 1     public static void main(String[] args) {
2 Connection conn = null;
3
4
//I am comfortable now
5 if (lookupClass()) return;
6
7
try {
8 conn = DriverManager.getConnection(
9 "jdbc:mysql://localhost/petshop", "root", "changeme");
10 Statement statement = conn.createStatement();
11 } catch (SQLException e) {
12 e.printStackTrace();
13 }
14 }
15
16
private static boolean lookupClass() {
17 try {
18 Class.forName("com.mysql.jdbc.Driver");
19 } catch (ClassNotFoundException e) {
20 e.printStackTrace();
21 System.out.println("Driver not found");
22 return true;
23 }
24 return false;
25 }
26