IntelliJ IDEA 2021.1 Help

Extract constant

The Extract Constant refactoring makes your source code easier to read and maintain. It also helps you avoid using hardcoded constants without any explanations about their values or purpose.

  1. In the editor, select an expression or declaration of a variable you want to replace with a constant.

  2. Press Ctrl+Alt+C to introduce a constant or select Refactor | Extract | Constant.

    Extract constant
  3. Select a name from a list that opens or type your own name and press Enter.

    Alternatively, press Ctrl+Alt+C twice to open the Extract Constant dialog where you can specify the additional options for the constant such as making it private or public, move the constant to another class, and so on.

    the Extract Constant dialog

Example

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 extacts 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) { } }

The Extract Constant refactoring helps you avoid using hardcoded constants without any explanations about their values or purpose.

Extract constant

Extract a constant

  1. In the editor, select an expression or declaration of a variable you want to replace with a constant.

  2. Press Ctrl+Alt+C to introduce a constant or select Refactor | Extract/Introduce | Constant from the main or context menu.

  3. If there are several expressions available for extracting, select the required one from the list that opens and press Enter.

  4. Select a name for the constant from the list of suggestions that opens or type a new one.

  5. Check the Put to header checkbox if you want the constant to be moved to the header file.

  6. Uncheck the Declare static checkbox if you don't want the constant to be declared as static.

  7. Press Enter.

Code example

BeforeAfter
@implementation PasswordValidator + (BOOL)isPasswordValid:(NSString *)password { // 4 will be extracted to a constant return password.length > 4; } @end
// Extracted constant static const int kMinPasswordLength = 4; @implementation PasswordValidator + (BOOL)isPasswordValid:(NSString *)password { return password.length > kMinPasswordLength; } @end
    Last modified: 21 June 2021