Skip to content

Class Extract Method

Sourcery refactoring id: class-extract-method

Description:

Extracts duplicate pieces of code in different functions in a class into their own methods

Requires Sourcery Pro

Before:

class ExtractionExample:
    def method_one(self):
        self.speed_slider = Scale(
            self.parent, from_=1, to=10, orient=HORIZONTAL, label="Speed"
        )
        self.speed_slider.pack()
        self.speed_slider.set(DEFAULT_SPEED)
        self.speed_slider.configure(background="white")

    def method_two(self):
        self.force_slider = Scale(
            self.parent, from_=1, to=10, orient=HORIZONTAL, label="Force"
        )
        self.force_slider.pack()
        self.force_slider.set(DEFAULT_FORCE)
        self.force_slider.configure(background="white")

After:

class ExtractionExample:
    def method_one(self):
        self.speed_slider = self._extracted_from_method_two_2("Speed", DEFAULT_SPEED)

    def method_two(self):
        self.force_slider = self._extracted_from_method_two_2("Force", DEFAULT_FORCE)

    # TODO Rename this here and in `method_one` and `method_two`
    def _extracted_from_method_two_2(self, label, arg1):
        result = Scale(self.parent, from_=1, to=10, orient=HORIZONTAL, label=label)
        result.pack()
        result.set(arg1)
        result.configure(background="white")
        return result

Explanation:

Do not Repeat Yourself (DRY) is an important tenet of writing clean, maintainable code. Duplicated code bloats the code base, making it harder to read and understand. It often also leads to bugs. Where changes are made in only some of the duplicated areas unintended behaviour will often arise.

One of the main ways to remove duplication is to extract the common areas into another method and call that. Sourcery can detect areas of duplicate code that are in different functions in the same class and extract them. It is recommended that you then rename the extracted function and any arguments that have not been automatically named. In the above example a suitable method name would be create_slider, and arg1 would be default_value.

Note that this refactoring only runs when a file is opened or saved - it does not get triggered whenever you change the code in a file.

Back to top