Select Page

Speaking more languages – 15 minutes

Since we have refactored some code into a base class and have now implemented the SSH class, we’re ready to add a new protocol. Let’s get this bad boy talking over Telnet. It’s actually a relatively small implementation to create the TelnetHost class. But first we need to do a little extra setup so the program knows what which protocol to use for each device.

We could use something like a digit to differentiate between SSH and Telnet hosts. However, that would not be very descriptive when you come back a year from now and look at the program. Let’s contrast the two possibilities.

Imagine it’s a year later and we are looking back at this program and see that first if statement. We would be baffled as to what on Earth the 2 might mean in the if statement. However in the second ifstatement we are using an enumeration. The enumeration lets us use an English-like word instead of a very arbitrary-seeming digit like 2.

We can make up our own definitions for an enumeration. In this case we are creating an enumeration named HostProtocol. The enumeration has two values defined: HostProtocol.ssh and HostProtocol.telnet. Additionally we are specifying the actual value for each of the enumeration values. Defining our enumeration is done easily:

In this iteration of our program we make use of the enumeration values in a couple of places. First we use the enumerations to specify the appropriate protocol for each of our devices when we record the devices in our database:

Later, when reading from the database, we use the enumeration values to figure out the appropriate class to instantiate to handle communicating with the device.

The if statements test the host_type from the database against each of the enumeration values. Being a little paranoid, we have an else branch that raises an exception. The reason for adding that is to protect against future mistakes. For example, a few months from now we might accidentally add some new host_type value in the database. By having the else branch we’ll quickly realize the mistake. A paranoid programmer is likely to have the paranoia justified at some point.

The enumeration is interesting from the general programming point of view, but the real value in this new chunk of code is that we are now making use of our two different classes to communicate with our host devices. Both TelnetHost and SSHHost derive from our base class HostDevice and each one implements its own protocol-specific methods.

It’s super cool that we can create a new host instance in any branch of the if statement and use the same method, host.read_config_and_save_to_file(), to do the actual work. At this point we have encapulated the functionality in one method. When we’re writing our code to read from the host devices we don’t want to know, don’t need to know, what protocol we’re using. We just use the correct method and it uses its own implementation.

Share This