Extract constant
Refactor | Extract/Introduce | Constant
CtrlAlt0C
The Extract Constant refactoring makes your source code easier to read and maintain. It also helps you avoid usage of hardcoded constants without any explanation about their values or purpose.
In the editor, select an expression or declaration of a variable you want to replace with a constant.
Press CtrlAlt0C to introduce a constant or select Refactor | Extract | Constant in the main menu.
Alternatively, on the toolbar that appears, click Extract and select Constant.
note
By default, IntelliJ IDEA uses the in-place refactoring. To use the Extract Constant dialog for the refactoring, open the Settings dialog (CtrlAlt0S) , go to Editor | Code Editing, and select the In modal dialogs refactoring option in the Refactorings area.
Select a name from a list that opens or type your own name and press Enter.
Alternatively, press CtrlAlt0C twice to open the Extract Constant dialog where you can specify the additional options for the constant such as making it
private
orpublic
, move the constant to another class, and so on.tip
Use mnemonics to quickly change visibility. For example, press Alt to display mnemonics and then press V to change visibility to
private
Let's introduce a constant for the expression "string"
that occurs twice throughout code.
public class Class {
public void method() {
ArrayList list = new ArrayList();
list.add("string");
anotherMethod("string");
}
private void anotherMethod(String string) {
}
}
IntelliJ IDEA extracts the constant and replaces the expression with the constant STRING
.
public class Class {
private static final String STRING = "string";
public void method() {
ArrayList list = new ArrayList();
list.add(STRING);
anotherMethod(STRING);
}
private void anotherMethod(String string) {
}
}
Thanks for your feedback!