Extracting methods

Extracting methods is arguably one of the most common aspects of refactoring. In general, it is the process of taking a block of code, which specializes in a specific task, outside of the current context it is being used in and converting it into a method/function.

Doing this is generally good practice in programming and has the advantages of readability and extendibility. For example, by moving a specific block of code into its own method/function, that logic can be reused in other places in the program, without the programmer having to copy and paste that block of code. Having some functionality that is used a lot through a program inside a separate function is intuitively a good way to structure your code as well.

Turning our attention to the aforementioned draw() method, we can see that the usage of the arrow() function from the matplotlib.pyplot module to draw the axis arrows (lines 45 - 48) is quite repeatable. In other words, we would like to extract these two lines of code into a function that takes in the four measurements of the axis (left, right, top, bottom) and evokes the plt.arrow() function twice. Let's get started:

  1. To do this, select the four lines of code and go to Refactor | Extract | Method... to perform the extraction (note the keyboard shortcut for future use):

Extracting a method
  1. Another familiar pop-up window will appear and ask for the name of the method to be extracted.
  2. We will enter draw_arrow for now.
  3. Also, note that you can specify which parameters the newly extracted method will take in the Parameters section of the pop-up window by checking and unchecking particular options.
  4. Finally, Signature preview gives you one last chance to check what the signature of the method will look like before we actually extract the code.
  5. For now, hit the OK button. You will see that not only are the two instances of the plt.arrow() function being called moved to a completely new function with the appropriate signature, but also that the code within the old draw() function is also edited appropriately (that is, the new draw_arrow() function is now being called within draw()):
    ...
# axis arrows
left, right = ax.get_xlim()
bottom, top = ax.get_ylim()
Point.draw_arrow(bottom, left, right, top)

plt.grid()
plt.show()


@staticmethod
def draw_arrow(bottom, left, right, top):
plt.arrow(left, 0, right - left, 0, length_includes_head=True,
head_width=0.15)
plt.arrow(0, bottom, 0, top - bottom,
length_includes_head=True,
head_width=0.15)

Also note that, if the code being extracted returns some value, the new method will also return the same value in a consistent way. This feature allows us to achieve a fairly complex refactoring task with the click of a button.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.204.208