Extract constant
The Extract Constant refactoring helps you eliminate hard-coded constants, making your code easier to read and maintain.
Extract a constant in-place
The in-place refactorings are enabled in CLion by default. So, if you haven't changed this setting, the Extract Constant refactoring for C/C++ is performed in-place, right in the editor.
Place the cursor within the expression or declaration of a variable to be replaced by a constant.
Do one of the following:
Press Ctrl+Alt+C.
Choose Refactor | Extract | Constant on the main menu or from the context menu.
If more than one expression is detected for the current cursor position, the Expressions list appears. If this is the case, select the required expression. To do that, click the expression. Alternatively, use the Up and Down arrow keys to navigate to the expression of interest, and then press Enter to select it:
If more than one occurrence of the expression is found within the class, specify whether you wish to replace only the selected occurrence, or all the found occurrences with the new constant.
Specify the name of the constant. Select the name from the list or type the name in the box with a red border.
To complete the refactoring, press Tab or Enter.
If you haven't completed the refactoring and want to cancel the changes you have made, press Escape.
Note that sometimes you may need to press the corresponding key more than once.
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
|