Extract method
The Extract Method refactoring lets you take a code fragment that can be grouped, move it into a separated method, and replace the old code with a call to the method.
In the JavaScript context, this refactoring always results in a function.
In the PHP context, the result of applying the Extract Method refactoring depends on the location of the selected code fragment:
If the selection is made inside a method of a class, the refactoring extracts a method.
If the selection is made inside a function or a script, the refactoring extracts a function.
Extract method
Select a code fragment you want to extract to a method.
Press Ctrl+Alt+M or go to
in the main menu.Alternatively, on the floating toolbar that appears when a code fragment is selected, click Extract and select Method.
Press Enter to apply the change.
By default, this extract refactoring will be applied in the editor via in-line controls. To change your settings to apply the refactoring via a modal, open the Settings dialog (Ctrl+Alt+S) , go to Editor | Code Editing, and in the Refactorings area select In modal dialogs.
Extract PHP method example
Extract PHP function example
Code examples
Before | After |
---|---|
private func setupUI() {
// ...
// This code will be extracted to a method
self.buttonLogin.layer.borderColor = UIColor.black.cgColor
self.buttonLogin.layer.borderWidth = 1.0
self.buttonLogin.setTitleColor(UIColor.black, for: .normal)
self.buttonLogin.setTitle("Login", for: .normal)
}
|
private func setupUI() {
// ...
// Extracted method's call
setupLoginButton()
}
// Extracted method
private func setupLoginButton() {
self.buttonLogin.layer.borderColor = UIColor.black.cgColor
self.buttonLogin.layer.borderWidth = 1.0
self.buttonLogin.setTitleColor(UIColor.black, for: .normal)
self.buttonLogin.setTitle("Login", for: .normal)
}
|
Before | After |
---|---|
- (void)setupUI {
// ...
// This code will be extracted to a method
self.buttonLogin.layer.borderColor = [[UIColor blackColor] CGColor];
self.buttonLogin.layer.borderWidth = 1.0;
[self.buttonLogin setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.buttonLogin setTitle:@"Login" forState:UIControlStateNormal];
}
|
- (void)setupUI {
// ...
// Extracted method's call
[self setupLoginButton];
}
// Extracted method
- (void)setupLoginButton {
self.buttonLogin.layer.borderColor = [[UIColor blackColor] CGColor];
self.buttonLogin.layer.borderWidth = 1.0;
[self.buttonLogin setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[self.buttonLogin setTitle:@"Login" forState:UIControlStateNormal];
}
|