Hacker News new | ask | show | jobs
by politician 588 days ago
This example isn't particularly good code. If you've got "lots of code" that names a bunch of variables (e.g. using ':=') that are never referenced AND you have a good reason not to do so (which I doubt: given this context it looks like an incomplete test), then predeclare these 'excess' variables:

   func TestWhatever(t *testing.T) {
        var resp3, resp4, fooBefore, subFoo, bar2, barNew, zap2 theirType

        // ...lots of code
   }
Alternatively, use '_' where they are being defined:

   // instead of
   resp2, err := doit()

   // use
   _, err := doit()
If, and given this context it's likely, you're checking these errors with asserts, then either change the name of the error variable, predeclare the err name (`var err error`), or split it into multiple tests instead of one giant spaghetti super test.

That said, in a code review, at a minimum, I would probably ask that these variables be checked for nil/default which would completely eliminate this problem.

1 comments

This is not a piece of code I would commit, obviously! It's a piece of code in the middle of being written and re-written (and re-run, a la REPL), and constantly replacing "resp2" with "_" and back again with "resp2" is friction. Go doesn't have REPL but having a TestWhatever(t *testing.T) function is a mostly good enough replacement, except for this one small problem.
Whew, that's a relief! If I understand correctly, then I think you'll have a better experience if you practice doing something like this when writing tests:

  foo, fooErr := doit()
  require.NotNil(foo)
  require.NoError(fooErr)
  _, _ = foo, fooErr // alternative if you don't want the asserts for some reason, remember to come back later and delete though

  // ...repl churn code... 
Using the stretchr/testify/require package. This code defines both variables, gives the error a unique name in the scope, and then references the names in two asserts. You won't have to deal with unreferenced name errors in the "repl churn", so you can comment/uncomment code as you go.