Extract Duplicate Method¶
Sourcery refactoring id: extract-duplicate-method
¶
Description:¶
Identifies duplicate sections of code in a function and extracts these into their own method
Requires Sourcery Pro
Before:¶
def extraction_example():
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")
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:¶
def extraction_example():
self.speed_slider = _extracted_from_extraction_example_2(
self, "Speed", DEFAULT_SPEED
)
self.force_slider = _extracted_from_extraction_example_2(
self, "Force", DEFAULT_FORCE
)
def _extracted_from_extraction_example_2(self, label, arg2):
result = Scale(self.parent, from_=1, to=10, orient=HORIZONTAL, label=label)
result.pack()
result.set(arg2)
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 the same function 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
arg2
would be default_value
.