-
Notifications
You must be signed in to change notification settings - Fork 80
Upcoming changes
These changes are now available to our beta testers!
Sourcery can now perform class-level refactorings. The first one is extracting duplicate code into methods at the class level.
Normally Sourcery scans for refactorings on every code change. Class-level ones need to do more analysis, so this will only run on file open and save.
Extract duplicate code from different methods into a new one
Requires Sourcery Pro
class TestClass:
def extraction_example(self):
self.speed_slider = Scale(
self.master, 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 intervening_function(self):
if True:
pass
def next_example(self):
self.force_slider = Scale(
self.master, from_=1, to=10, orient=HORIZONTAL, label='Force')
self.force_slider.pack()
self.force_slider.set(DEFAULT_FORCE)
self.force_slider.configure(background='white')
class TestClass:
def extraction_example(self):
self.speed_slider = self._extracted_from_next_example_2('Speed', DEFAULT_SPEED)
def intervening_function(self):
if True:
pass
def next_example(self):
self.force_slider = self._extracted_from_next_example_2('Force', DEFAULT_FORCE)
def _extracted_from_next_example_2(self, label, arg1):
result = Scale(self.master, from_=1, to=10, orient=HORIZONTAL, label=label)
result.pack()
result.set(arg1)
result.configure(background='white')
return result
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 methods 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
.
Class-level refactorigns such as this one run on file open and file save, rather than on every change to the code.
Please visit our newer docs at https://docs.sourcery.ai