Skip to content

Extract method

Sourcery refactoring id: extract-method

Description:

Extracts complex pieces of functions into their own methods

Requires Sourcery Pro

Before:

def func(self):
  if typed and self.current_char == '(':
    pos = self.pos
    try:
      pass
    except DefinitionError as exParamQual:
      self.pos = pos
      try:
        pass
      except DefinitionError as exNoPtrParen:
        self.pos = pos
        msg = "If parenthesis in noptr-declarator"
        if paramMode == 'function':
          msg += " (e.g., 'void (*f(int arg))(double)')"
        prevErrors.append((exNoPtrParen, msg))
        header = "Error in declarator"
        raise self._make_multi_error(prevErrors, header)

After:

def func(self):
  if typed and self.current_char == '(':
    pos = self.pos
    try:
      pass
    except DefinitionError as exParamQual:
      self.pos = pos
      try:
        pass
      except DefinitionError as exNoPtrParen:
        self._extracted_from_func_11(pos, exNoPtrParen)

def _extracted_from_func_11(self, pos, exNoPtrParen):
  self.pos = pos
  msg = "If parenthesis in noptr-declarator"
  if paramMode == 'function':
    msg += " (e.g., 'void (*f(int arg))(double)')"
  prevErrors.append((exNoPtrParen, msg))
  header = "Error in declarator"
  raise self._make_multi_error(prevErrors, header)

Explanation:

Methods are much more readable if they are short, and if every line of code is at the same rough level of abstraction.

This refactoring takes long blocks from functions and extracts them into their own method. It will only trigger for large blocks that are possible to extract, and where the remainder of the method is sufficiently long.

It is recommended that you then rename the extracted function and any arguments that have not been automatically named. Here a suitable method name would be handle_noptr_exception.

Back to top