Reordering function arguments

Another common refactoring operation is to change the function arguments. Let's look at reordering arguments, since findings from this example can also be applied to other situations.

Here is a sample method in animal.py:

def act(self, target, verb):
return 'Suddenly {kind} {verb} at {target}!'.format(
kind=self.kind,
verb=verb,
target=target)

The order of arguments in this method doesn't seem very intuitive. We might be better off changing it to look like this:

def act(self, verb, target):
return 'Suddenly {kind} {verb} at {target}!'.format(
kind=self.kind,
verb=verb,
target=target)

However, there are quite a few callers for this method already, since we also use the method in farm.py (the code is intentionally repetitive for illustration purposes):

def act(self, target):
for animal in self.animals:
if animal.get_kind() == 'cat':
print(animal.act(target, 'meows'))
elif animal.get_kind() == 'dog':
print(animal.act(target, 'barks'))
elif animal.get_kind() == 'sheep':
print(animal.act(target, 'baas'))
else:
print(animal.act(target, 'looks'))

This looks like a job for regular expressions! Let's write one up:

:arg **/*.py
:argdo %s/v<act>((w{-1,}), ([^,]{-1,}))/act(2, 1)/gec | update

Give it a shot, and you will be greeted by a confirmation screen for every one of your matches (as we specified the c flag for the :substitute command):

To break it down, we have the following:

  • v sets the magic mode for this string to very magic, to avoid having to escape every special character.
  • <act>( matches the literal string act(, ensuring that act is a whole word (so partial matches such as react( would not be picked up).
  • (w{-1,}), ([^,]{-1,})) defines two groups separated by a comma and a space, and followed by a closing parenthesis. The first group is a word of at least one character, while the second is any character string of at least one character, excluding commas (this way we'll match act(target, 'barks'), but not act(self, target, verb)).
  • Finally, act(2, 1) places the two matching groups in reverse order.
..................Content has been hidden....................

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