Fun with Refactoring

Do you find yourself writing a whole bunch of repeating sections of code that look, for instance, like this:

TextView nameCol = new TextView(this);

nameCol.setTextColor(getResources().getColor(R.color.title_color)); nameCol.setTextSize(getResources().

getDimension(R.dimen.help_text_size)); nameCol.setText(scoreUserName); table.addView(nameCol);

This code sets text color, text size, and text. If you've written two or more blocks that look like this, your code could benefit from refactoring. Eclipse provides two very useful tools—Extract Local Variable and Extract Method—to speed up this task and make it almost trivial.

Follow these steps to use the Extract Local Variable tool:

1. Select the expression getResources().getColor(R.color.title_color).

2. Right-click and choose Refactor, Extract Local Variable (or press Ctrl+Alt+L).

3. In the dialog that appears, enter a name for the variable and leave the Replace All Occurrences check box selected. Then click OK and watch the magic happen.

4. Repeat steps 1-3 for the text size. The result should now look like this:

int textColor = getResources().getColor(R.color.title_color);

float textSize = getResources().getDimension(R.dimen.help_text_size);

TextView nameCol = new TextView(this);





All repeated sections of the last five lines also have this change made. How convenient is this?

Now you're ready for the second tool. Follow these steps to use the Extract Method tool:

1. Select all five lines of the first block of code.

2. Right-click and choose Refactor, Extract Method (or choose Ctrl+Alt+M).

3. Name the method and edit the variable names anything you want. (Move them up or down, too, if desired.) Then click OK and watch the magic happen. By default, the new method is below your current one.

If the other blocks of code are actually identical, meaning the statements of the other blocks must be in the exact same order, the types are all the same, and so on, they will also be replaced with calls to this new method! You can see this in the count of additional occurrences shown in the dialog for the Extract Method tool. If that count doesn't match what you expect, check that the code follows exactly the same pattern.

Now you have code that looks like the following:

addTextToRowWithValues(newRow, scoreUserName, textColor, textSize);

It is easier to work with this code than with the original code, and it was created with almost no typing! If you had ten instances before refactoring, you've saved a lot of time by using a useful Eclipse tool.

Was this article helpful?

0 0

Post a comment