|
-
December 14th, 2009, 12:51 PM
#1
[RESOLVED] Transactional programming - how do you solve it? (no DB here)
This time I'd like to ask you how do you solve such a problem that there are few steps that have to be performed in a method but it's like a transaction, this means if one step fails the function returns false.
I know three ways how to do it. With the last one I just came up today and currenty it's my favourite. Here they are:
1:
Code:
bool DoSomething()
{
bool success = false;
try
{
if(DoSomethingElse1() == false)
throw new Exception("Some description");
// ... more code here
if(DoSomethingElse2() == false)
throw new Exception("Something else2 went wrong.");
success = true;
}
catch(Exception ex)
{
// ...
}
finally
{
// ... some clean up etc.
}
return success;
}
Try/catch is a very clear way to do it, but the performance drops when the function gets called many times and it often fails.
2:
Code:
bool DoSomething()
{
if(DoSomethingElse1() == false)
{
// .. do some clean up here etc.
return false;
}
// ... more code here
if(DoSomethingElse2() == false)
{
// .. do some more clean up
return false;
}
return true;
}
this one I think is quite fast but I have to clean up on each fail so it is lots of redundant code.
3:
Code:
bool DoSomething()
{
bool success = false;
do
{
if(DoSomethingElse1() == false)
break;
// ... more code here
if(DoSomethingElse2() == false)
break;
success = true;
}
while(false);
// ... some clean up etc.
return success;
}
so, this is my latest invention ;]
what do you think about all of them? have you other ways to do this kind of transaction in your code?
win7 x86, VS 2008 & 2010, C++/CLI, C#, .NET 3.5 & 4.0, VB.NET, VBA... WPF is comming
remeber to give feedback  you think my response deserves recognition? perhaps you may want to click the Rate this post link/button and add to my reputation
private lessons are not an option so please don't ask for help in private, I won't replay
if you use Opera and you'd like to have the tab-button functionality for the texteditor take a look at my Opera Tab-UserScirpt; and if you know how to stop firefox from jumping to the next control when you hit tab let me know
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|