Sunday, April 19, 2020

The importance of Unit Tests... and failure.

A project I work on was implemented without considering organized unit testing.  Some of the packages (python) do have tests tacked onto the __main__ portion of the package but it is willy nilly.  So I am slowly creating an alternate code base with minor packaging improvements and unit tests for everything.

The beauty of unit tests is that as your code becomes more and more complex (and let's face it, code does not tend to trend in the other direction) any little change that might affect a consumer class, will be caught.  For example say I have a bunch of enums used by any number of classes but a NEW class wants a change to that enum.  You will find out very quickly if the change to the enum breaks all the other consumers of that class, right?  Might work for one, might break 10 others.  So anyway, it is a useful tool, albeit now when you write code or change code you are writing more unit tests as well.  I still think it greatly out weighs the additional time spent.

In a way it replaces the idea of test-driven development.  This isn't EXACTLY the same thing... it is creating tests around positive and negative test cases for a class (or code) you have created.  With test-driven development the concept is a little deeper, you spend a great deal of time up front designing success and failure cases... defining all possible inputs and outputs.  I think (and perhaps this shows ignorance on my part) that these days developers don't really think along those lines.  They create a service or a class and pass back values that they deem appropriate without a lot of deep thought put into PLANNING for failure.

This, by the way, is a reason I really appreciated Grady Booch.  His belief was that you PLAN errors.  Errors are something your code should consider.  If your code is solid, the only place an error can come from would be the inputs it receives for processing.  Outside of that (and in this day and age there are plenty) there are environmental issues that can affect code.  Those, of course, are more difficult to build into your code, instead you just blindly trap and throw for the most part.  I never really liked that but as long as whoever is consuming your code is able to trap and decision on errors... things should work out.

Even so, people sometimes do strange things in their code...


No comments: