Extract constant
As Extract Variable, the Extract Constant refactoring lets you extract a specified value to a corresponding constant.
The animation below demonstrates how to extract a specific word from a string to a constant:
To extract a constant:
Select a value to refactor or place a caret at a string containing the required value.
From the main menu, select
Ctrl+Alt+C.(Optional) If you place a caret at a place containing several expressions available for extracting, select the required expression and press Enter:
(Optional) If more than one occurrence of the expression is found, specify whether you wish to replace only the selected occurrence or all the found occurrences with the new variable:
Specify the constant name and press Enter.
Example
The Extract Constant refactoring helps you avoid using hardcoded constants without any explanations about their values or purpose.
Extract a constant
In the editor, select an expression or declaration of a variable you want to replace with a constant.
Press Ctrl+Alt+C to introduce a constant or select
from the main or context menu.If there are several expressions available for extracting, select the required one from the list that opens and press Enter.
Select a name for the constant from the list of suggestions that opens or type a new one.
Check the Put to header checkbox if you want the constant to be moved to the header file.
Uncheck the Declare static checkbox if you don't want the constant to be declared as
static
.Press Enter.
Code example
Before | After |
---|---|
@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
|