Specificity is almost always a good thing.
But sometimes when unit testing, I need to pass dummy values to functions just to make the compiler happy.
I don’t care what the values are, but using specific literals can obscure the intent of the tests:
This test checks that the number of things on a stack is correct after pushing some strings onto it.
Somebody coming across this test may have a few questions: is it important that these particular values are pushed? Is the duplication of
In fact, it doesn’t matter what is pushed onto the stack, so this test shouldn’t introduce any doubt in the mind of the reader.
In such cases I often make a helper function:
Now I can clarify the intent of the test: it’s the action of pushing I care about, not the values I push:
I use the same trick for
Int values, and indeed any other time I need a dummy value of a particular type:
But what if I need a dummy
String and a dummy
Int? Won’t the two
any() function names clash? Will I need to uglify them to
Fortunately, Swift functions can be overloaded not only by their name and parameter types, but also by their return type. That means these functions can coexist:
So I can write tests that use
any() wherever I don’t care about the value and it will do the right thing:
This trick is not confined to primitive Swift types either. I use it for all sorts of things, including my own complex types:
Sometimes it’s better to be, you know, kind of vague-ish. Or whatever.