Great feedback. Let's explore some ideas for a bit shall we.
So here is the test code with the magic numbers in it. The magic numbers being the "1" and the "10".
The technique I discussed in the linked article was to wrap the magic numbers in methods as a means to give them some context. i.e. a name.
One feedback point was that it was unclear how this approach is better than having badly named constants. I'm going to say that we're sensible enough to give the constants meaningful names, so let's try it
One advantage of this approach is that you can now reuse the constants. The downside for me is that the constants LOOK A BIT SHOUTY.
Another feedback point was to use local variables to hold the values. Here goes
I'm not against this approach at all and I think it is better than using shouty constants. The values are declared close to the assertion which is a good thing. My only gripe is that I've just doubled the number of lines of code in my test.
So all of this has gotten me thinking a bit deeper into this particular example and how I can improve upon it. My initial though is to introduce some DSL (Domain Specific Language) into my test case to help convey the intent. My first step was to abstract away the object creation of Range into a method that provides some context to the parameters.
Then I decided I didn't need the local variable if I inlined it into the assertThat line
But then I didn't think it read very well. The "isInRange(11)" part just didn't look right. So I refactored that method name.
At this point I'm pretty happy with how the test has turned out. The test case is down to a single line of code and I think the intent and language is clear.
While working on the readability of my test I discovered a better name for the "isInRange" method in the production code. Renaming it to "contains" has now made the method more intuitive to use and portrays its intent more clearly. I started off trying to improve my tests, and ended up improving my production code too. For me that's a massive win.
E Armitage: I'm awarding you a
cow for inviting me to think quite hard about your feedback.