Hi Ben,Â
Sorry, I've misread that part.Â
Now that I got some sleep and reviewed your code a little bit more, it looks like you got trapped by your own design decisions.Â
First of all, variable shadowing is something every Go developer should be able to handle gracefully, but I understand your concern about how easy it's to miss that bug. Doesn't the linter alert you about that shadowing process? Just curious about that.Â
Then, the mistake, IMHO, is the use of the defer function and the custom tx.Close method (is it custom made, right? I haven't found a reference for that method in the sql.Tx type docs) that "saves" you from manually handling tx.Commit() vs tx.Rollback() calls, which if you think, it gets pretty well aligned to the error handling philosophy of Go. If you get an error, please go ahead and explicitly handle that error.Â
So, your DoTwoThings() function is actually doing 3 things, the 2 things against the DB, but it's also handling the transaction. If you see these 2 DB queries as a unit, you may want to put these in a method that takes a sql.Tx object, executes queries in that context and return an error result that will indicate if all of them were successful or not. Then you Commit or Rollback the transaction in the caller, not in a deeper level.Â
So pretty much as your Transact() method, but I'm not a fan of the defer use there, while I get how you managed to also catch panics there.Â
Out of your 2 proposals, I like this one better.Â
But if you ask me, I'd recommend to avoid the defer use, which is the thing that's actually causing the shadowing problem, and to enforce the manually handling of the transactions directly related to error handling. That's how I've been doing it and it's pretty clear and straightforward when you read that code, the Rollbacks after the errors and the Commits at the end of each function are just there, explicitly telling you what's happening when some DB query fails.Â
But again, it's a matter of opinion, design and personal preferences.Â
I just hope this helps for you to form an opinion.Â
Best!
Leonel Quinteros
Director of TechnologyÂ