AppCode 2021.2 Help

Extract function

The Extract Function refactoring lets you take a code fragment that can be grouped together, move it into a separated function and replace the old code with the function call.

The Extract Function refactoring has the following limitations:

  • Refactoring does not work with multiple output values in the automatic mode. You have to change your code before applying the refactoring, for example, you may introduce a special data-class that contains all output values.

  • Refactoring does not work for a code fragment which conditionally returns from the containing method and is not placed at the end of it.

Extract function

To reverse the Extract Function refactoring, press ⌃ ⌥ N to invoke the Inline refactoring.

Extract a function

  1. Select a code fragment you want to extract to a function.

  2. Press ⌃ ⌥ M or from the main or context menu, select Refactor | Extract/Introduce | Function.

  3. In the dialog that opens, configure function options, such as visibility, parameter names, selector parts (for Objective-C), and so on. You can also change a name of the method if you need.

  4. Click Extract.

Code examples

BeforeAfter
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) }
BeforeAfter
- (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: 26 August 2021