Home > Mobile >  Extract method and insert call after original method call
Extract method and insert call after original method call

Time:10-20

I'm using PyCharm and I'm trying to do some refactoring but don't see how I'm able to do this in a fast and reliable way.

I have a method that does too many things and I want to extract a part into another method. The extracted method should not be called in the method it was extracted though, but rather in the calling method.

Current state

class User():
  def doStuff(self):
    calculateA()
    calculateB()
    calculateC()

def callerA():
  # do other things before
  obj.doStuff()

def callerAA:
  # do other things before
  obj.doStuff()

#... and many more methods calling doStuff method

Wanted

class User():
  def doStuff(self):
    calculateA()

  def doOtherStuff(self):
    calculateB()
    calculateC()

def callerA():
  obj.doStuff()
  obj.doOtherStuff()

def callerAA:
  obj.doStuff()
  obj.doOtherStuff()

#... and many more methods calling doStuff method and doOtherStuff

# Now I'll be able to create this new method only doing a subset of the original method
def aNewMethod:
   obj.doStuff()


Is this possible to do with PyCharm? Been playing around with the refactoring without any luck. Extracting into a method is the easy part I suppose but the method call will end up in the wrong place. If it's possible in Intellij I have a license for that as well so I can just switch.

CodePudding user response:

there is no such option. You are welcome to submit a feature request at https://youtrack.jetbrains.com/issues/PY Information on how to use YouTrack: https://intellij-support.jetbrains.com/hc/en-us/articles/207241135-How-to-follow-YouTrack-issues-and-receive-notifications

CodePudding user response:

Step1: Extract two new methods into your User class

This:

class User():
  def doStuff(self):
    calculateA()
    calculateB()
    calculateC()

Becomes:

class User():
  def doStuff(self):
    newMethodA()
    newMethodB()

  def newMethodA(self):
    calculateA()

  def newMethodB(self):
    calculateB()
    calculateC()

Step 2: Inline doStuff method

class User():

  def newMethodA(self):
    calculateA()

  def newMethodB(self):
    calculateB()
    calculateC()

def callerA():
  newMethodA()
  newMethodB()

def callerAA():
  newMethodA()
  newMethodB()

Step 3: Rename methods

  • Related