Refactoring
Refactoring – 5 minutes
When we consider what’s going on in these classes there are some subtle improvements we can make. For example, our TelnetHost and our SSHHost classes each have their own send_command_and_get_response() method. And they do the same thing. We try not to repeat ourselves (DRY) in code because saying the same thing int two different places opens up places for new bugs. Not desirable.
We had defined decorated our send_command_and_get_response() method with @abc.abstractmethod in our base class HostDevice. In this iteration we need to remove the decorator which will make the method a concrete method. The method also needs a body. Here’s what it looks like in HostDevice:
def send_command_and_get_response(self, cmd):
"""Sends command to device and figures out how to get response, based on protocol"""
if not cmd.endswith("\n"):
cmd += "\n"
self.send_command(cmd)
results = self.get_command_results()
return results
Note that the decorator is now gone. The method in HostDevice now contains the logic. Since the logic is now in the base class we can remove the send_command_and_get_response() implementations from both SSHHost and TelnetHost. Go ahead, delete them. For reals.
