Humble Objects

Humble Objects

Ego is the Enemy. Ego can cause us all kinds of problems in our personal and professional lives. When it comes to software, it is no different. Objects and VIs that have large egos create problems. One of the problems they cause is that they make it very hard for us to test our code. What does it mean for an object or VI to have a large ego? It means it tries to take on too many responsibilities.

Here is an example of some hard to test code. This method is not very humble.

In the example above, the method is not only writing to the serial port but also formatting the string as well. It is very difficult to test the logic for creating the string because we can’t call it separately. To test it we have to call the entire VI, which requires us to use the serial port. That makes it hard to verify the result (ie. the string that is written to the serial port). It also makes it harder to automate our testing. The solution is to introduce a Humble Object to separate the logic form the hard to test code (in this case the serial port).

Same Code Refactored to use a Humble Serial Port Object.

To make this code easier to test we introduce a Humble Serial Port Object. This object simply writes data to the serial port. That is why we call it humble. It only does one thing.We also extract the string logic into it’s own subvi.

Now we can test the logic for creating the string we are going to write to the serial port.

Now that the string logic is in its own subvi, we can drop it into a test method. Now we can test the logic completely separate from the serial port. We can now run the test automatically on any machine without worrying about serial port settings.

Where else can this idea be used? It works for talking to hardware via serial, TCP/IP, DAQmx, etc. It works for calling DLLs or Python functions. It works for GUIs. It works for databases. I am sure you can come up with other good use cases.