C# searching for new Tool for the tool box, how to template this code
Posted
by Nix
on Stack Overflow
See other posts from Stack Overflow
or by Nix
Published on 2010-03-31T15:53:56Z
Indexed on
2010/03/31
19:03 UTC
Read the original article
Hit count: 501
All i have something i have been trying to do for a while and have yet to find a good strategy to do it, i am not sure C# can even support what i am trying to do.
Example imagine a template like this, repeated in manager code overarching cocept function Returns a result consisting of a success flag and error list.
public Result<Boolean> RemoveLocation(LocationKey key)
{
List<Error> errorList = new List<Error>();
Boolean result = null;
try{
result = locationDAO.RemoveLocation(key);
}catch(UpdateException ue){
//Error happened less pass this back to the user!
errorList = ue.ErrorList;
}
return new Result<Boolean>(result, errorList);
}
Looking to turn it into a template like the below where Do Something is some call (preferably not static) that returns a Boolean. I know i could do this in a stack sense, but i am really looking for a way to do it via object reference.
public Result<Boolean> RemoveLocation(LocationKey key)
{
var magic = locationDAO.RemoveLocation(key);
return ProtectedDAOCall(magic);
}
public Result<Boolean> CreateLocation(LocationKey key)
{
var magic = locationDAO.CreateLocation(key);
return ProtectedDAOCall(magic);
}
public Result<Boolean> ProtectedDAOCall(Func<..., bool> doSomething)
{
List<Error> errorList = new List<Error>();
Boolean result = null;
try{
result = doSomething();
}catch(UpdateException ue){
//Error happened less pass this back to the user!
errorList = ue.ErrorList;
}
return new Result<Boolean>(result, errorList);
}
If there is any more information you may need let me know.
I am interested to see what someone else can come up with.
Marc solution applied to the code above
public Result<Boolean> CreateLocation(LocationKey key)
{
LocationDAO locationDAO = new LocationDAO();
return WrapMethod(() => locationDAO.CreateLocation(key));
}
public Result<Boolean> RemoveLocation(LocationKey key)
{
LocationDAO locationDAO = new LocationDAO();
return WrapMethod(() => locationDAO.RemoveLocation(key));
}
static Result<T> WrapMethod<T>(Func<Result<T>> func)
{
try
{
return func();
}
catch (UpdateException ue)
{
return new Result<T>(default(T), ue.Errors);
}
}
© Stack Overflow or respective owner