How To Write Untestable Code

So I’m going to sound off a bit on an awful bit of code I’ve come across.  I was tasked with adding a feature that involved creating a couple of structs that just hold data (of course) and then displaying that data in a “pop ussp” of sorts on a webpage.  The problem was that in order to build up the collection of structs I had to use a massive class that is the central piece of the system.  I will call that class “R”.  The R class holds TONS of references to other complex types and it also has some rather complex logic for doing some filtering on those types.  Therefore my “Builder” class which needs to build up the structs for display in the popup had to have the R class injected into it.  It needed not only data from R, but also some of R’s methods.

Because the API was poorly designed my “Builder” class needed to iterate and do some complex filtering and conditional logic on 4 different collections off of R.  I carefully designed my Builder to follow the Single Responsibility principle, and thus while the data it returned would feed a UI, it had no UI concerns of any kind within it.  It would be a great bit of code to unit test, especially since it was brand new.

Unfortunately the R class made this impossible.  It implemented no interfaces.  It had 5 constructors and the one with the fewest arguments had 24 different parameters, many  of which were other complex types.  Incidentally only 1 of the many complex types implemented an interface, the others were just like the R class and took in many othe subobjects in their constructor params.  This made unit test setup a downright impossibility. 

Some of the objects could literally only be newed up with data from the database. I tried subclassing R with “TestableR” so I could pass that into my Builder, but R had no default constructor so my TestableR class would’ve been required to invoke one of R’s constructors which left me right back where I started.

Why,  you may ask, did I not extract an interface for R, which would be a non-breaking change? Because in the organization who owns the code this is (for reasons unknown to me) and controversial and politically charged issue.  While that goes unresolved, most new code added to the system, no matter how well designed, is effectively untestable. Put this down as a Daily WTF.

Advertisement

No comments yet

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.