Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return Tuple<bool, string> instead of throwing exception()?

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?

like image 633
AZ. Avatar asked Mar 21 '12 18:03

AZ.


2 Answers

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); 
    }

}
like image 68
Amitabh Avatar answered Oct 06 '22 16:10

Amitabh


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"); 
}

}

like image 32
Shailesh Avatar answered Oct 06 '22 16:10

Shailesh