Java Reference
In-Depth Information
You can use the command Refactor | Introduce
Constant ( Ctrl+Alt+C ) to replace magic numbers
with a reference to a named static final field. To cre-
ate a constant, select an expression, number, String ,
or character, and execute the Refactor command.
You'll see a dialog like that shown in figure 9.18.
In this box, you define the name and visibility for
the constant you're about to create. IDEA suggests a
name, but you'll probably want to make up your own.
By convention, constants are named in all capital let-
ters, using the underscore character as a word sepa-
rator. Following this naming scheme immediately
tells someone reading your code that the purpose of
this field is to hold a constant value.
The option Replace all occurrences of expression is particularly handy. If it's
selected, IDEA replaces the selected expression with your new constant reference
throughout the current file, rather than just the one selected occurrence. The
number of occurrences that IDEA has found is shown in parentheses. After replac-
ing them for you (if you accept the option), IDEA highlights the changes in the
file, giving you a chance to quickly back out any inadvertent changes. For exam-
ple, if you're using 64 in a method call and also in some math (32 + 64), IDEA can
replace one or all of the values with the new constant.
Figure 9.18 The Introduce
Constant refactoring is used
to remove magic numbers
from your code.
Introducing a new field or local variable
Two other refactoring commands work like
the Introduce Constant refactoring: Intro-
duce Variable ( Ctrl+Alt+V ) and Introduce
Field ( Ctrl+Alt+F ). Both of these commands
are available through the Refactor menu. As
with constants, these refactoring operations
are used to replace an expression in your code
with a reference to a symbol so that its purpose
is clear. Select the expression and execute the
command, and you're presented with a dialog
similar to the one shown in figure 9.19, which
is simplified quite a bit when introducing a
variable rather than a field. As with converting
constants, the name and type are requested;
Figure 9.19 The Introduce Field option
is another commonly used refactoring.
 
 
 
 
Search WWH ::




Custom Search