I have a method Foo() does some hard work and on the UI layer I have a button to invoke that method.
All I want to do is call the method and show a messagebox if there is something wrong with the Foo() method.
I have two choices to design the method signature:
1.Tuple
Tuple<bool, string> Foo()
{
if(!DoHardWorkA()) return Tuple.New(false, "cannot do hardwork A");
if(!DoHardWorkB()) return Tuple.New(false, "cannot do hardwork B");
return Tuple.New(true, String.Empty);
}
2.Exception
void Foo()
{
if(!DoHardWorkA()) throw new ProgramSpecificException("cannot do hardwork A");
if(!DoHardWorkB()) throw new ProgramSpecificException("cannot do hardwork B");
return Tuple.New(true, String.Empty);
}
Both DoHardWorkA() and DoHardWorkB() are external methods that I don't have control of them, and they return true/false indicating the result.
Logically, I think I should go with option 2 as they are really exceptions; But for consistency, I'd like to go with option 1.
Which one do you prefer, why?
Throwing an Exception and handling it in consistent way is better.
If Foo fails for any other reason then also it will be handled. Suppose a scenerio.
void UIMethod()
{
Tuple<Result, Error> ret = Foo();
if(ret.Error)
MessageBox.Show(ret.Error);
}
Now because of change in requirement you have to call another method before Foo and it can also throw an exception. Then it becomes complex.
It is much easier to do this.
void UIMethod()
{
try{
MethodBeforeFoo();
var ret = Foo();
}
catch(Exception ex)
{
MessageBox.Show(ex.Message);
}
}
It really depends on your need. Modify your code like this, it will handle unhandled exceptions as well.
Tuple<bool, string> Foo()
{
try
{
if(!DoHardWorkA()) return Tuple.New(false, "cannot do hardwork A");
if(!DoHardWorkB()) return Tuple.New(false, "cannot do hardwork B");
return Tuple.New(true, String.Empty);
}
catch
{
return Tuple.New(false, "cannot do hardwork A");
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With