Extract method
The Extract Method refactoring allows you to extract a specified code fragment into its own method.
To extract a method:
Select a code fragment to refactor or place the caret at a string containing the required code fragment:
In the main menu, go to
Ctrl+Alt+M.In the Extract Method dialog, specify the method visibility, name and, optionally, parameter names:
Click OK to finish refactoring:
Example
class Hello
def greet
name = "JetBrains"
puts "Hello from #{name}"
end
end
class Hello
def greet
name = "JetBrains"
puts get_greeting(name)
end
private
def get_greeting(name)
"Hello from #{name}"
end
end
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];
}
|
Last modified: 08 October 2024