While my assumption may seem to sound subjective, after some research, I found that it\'s not uncommon to find developers who favour a dummy Try/Catch
instead of us
I'm entirely with you on the connection; that should be using
, and there is no need for the explicit Close()
. The transaction is a little bit trickier; the code shown is certainly overkill at the moment, but it is not entirely defined that Dispose()
should do a rollback. Actually, that is what tends to happen in every implementation I've looked at, but it is slightly vexing that even DbTransaction
(which most providers use) doesn't actually do this. Contrast to TransactionScope
where it is explicitly defined that a Dispose()
without a commit counts as a rollback. Because of that, I tend to use (excuse the C#):
using(var conn = GetOpenConnection())
using(var tran = conn.BeginTransaction()) {
try {
// TODO: do work
tran.Commit();
} catch {
tran.Rollback();
throw;
}
}
which is somewhere between the two in terms of complexity. It isn't messing around with null
-checks, at least.
What you're seeing is developers coding according to the documentation (a "Good Thing"). The base class DbTransaction (used for most data providers' transaction implementations) states clearly in its documentation:
Dispose should rollback the transaction. However, the behavior of Dispose is provider specific, and should not replace calling Rollback.