GoLand 2024.2 Help

Extract method

With the Extract Method refactoring, you can take a code fragment, move it into a separated method and replace the old code with a call to the method. If the code always exits in return statements (all execution paths lead to possibly implicit return statements), it is extracted as is. However, if it contains execution paths without returns, the extracted method will have an additional bool flag as a return value. The flag is used to perform an early return on the call side.

When you extract a function by using the Extract Method refactoring, GoLand keeps the original order of parameters of a parent function.

Extract functions and methods

  1. In the editor, select an expression or its part that you want to extract. You can also place the caret within the expression, in this case GoLand offers you a list of potential code selections.

  2. Press Ctrl+Alt+M or go to Refactor | Extract | Extract Method in the main menu.

  3. Type a method name and press Enter.

Code snippet at GitHub

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