I am using asp.net mvc and nhibernate with the unit of work pattern.
I have something like this
public bool IsSomething()
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff == null)
{
return false;
}
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse == null)
{
return false;
}
return true;
}
So in my if statements if something is null and I need it not to be null I just get out of the statement.
This is opposed as having nested if statements that could be like nested 4 or 5 times to do null checks.
public bool IsSomething()
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff != null)
{
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse != null)
{
// some more check heere ( could have another few if statements null checks here)
}
}
}
So I find the first way much easier to read then nested levels of if statements.
My problem is that even if you do a query in nhibernate you must wrap it around in a transaction and at the end do either a rollback or commit.
Option 1
public bool IsSomething()
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff == null)
{
unitOfWork.Commit();
return false;
}
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse == null)
{
unitOfWork.Commit();
return false;
}
unitOfWork.Commit();
return true;
}
This way I don’t like as you have to keep putting commit everywhere. If possible I would love to have just one commit(unless I have more than one unit of work transaction)
So then I though why not put it in a finally like this
public bool IsSomething()
{
try
{
unitOfWork.BeginTransaction();
var myGetStuff = repo.GetStuff(1);
if(myGetStuff == null)
{
return false;
}
var somethingElse = myGetStuff.GetSomethingElse();
if(somethngElse == null)
{
return false;
}
return true;
}
catch(Exception ex)
{
unitOfWork.RollBack();
}
finally
{
unitOfWork.Commit();
}
}
I like this but then I realized what happens if the commit fails? It won’t rollback and the exception won’t be caught.
So anyone else have any ideas?
This code of your looks rather problematic to me, especially when there are nested unit of work calls (how do you handle those?). What I would do is to open the unit of work (and the transactions) in the calling code (the Controller in your case as you use ASP.Net MVC) and not the IsSomething function. It would look something like this:
The IsSomething function would then look simply like this