Inline variable refactoring is used to remove redundant usage of variables. Consider our current distance() method in the Point class:
def distance(self, p):
diff = self - p
distance = sqrt(diff.x**2 + diff.y**2)
return distance
We can see that, after the distance variable is declared, it is immediately returned by the method. We would like to combine these two lines of code into one so that we can simply return the sqrt(diff.x**2 + diff.y**2) expression.
However, doing this, you might argue, can be seen as the opposite of how we defined the general purpose of refactoring; after all, by getting rid of a variable, we are potentially making our code less readable and extendable. The readability of our code will not be affected since we can easily guess that the expression being returned by a method named distance() is a distance quantity. Since the variable is being returned right away, there is no use in making the method extendable and allowing the variable to be used further. All in all, we can safely shorten and make this code simpler without any significant downsides.
This process is generally known as inlining variables. Let's go over this now:
- Getting back to our specific example in the distance() method, go ahead and select the two lines of code that we wish to combine and go to Refactor | Inline..., like so:
- A pop-up window will appear, informing us about the total number of instances where the variable will be inlined (there should be only one in this specific case). After this, the distance() method will be transformed into the following code, which is what we wanted:
def distance(self, p):
diff = self - p
return sqrt(diff.x ** 2 + diff.y ** 2)
We can see that the method is now more concise, but no readability has been lost. In practice, you also have the option of inlining various other components of a Python program (constants, fields, parameters, methods, and superclasses) using the same feature in PyCharm. More information can be found at www.jetbrains.com/help/pycharm/inline.html.