2011-04-28 65 views
3

如果你有一个蛮力搜索用户不知道数据类型,那么我们可以做这样的事情吗?在这种情况下嵌套尝试捕获合理吗?

 if (search.Length > 0 && comboBox1.Text.Equals("Data Type Not Known")) 
     { 
      try 
      { 
       ParentGraph p = new ParentGraph(search); 
      } 
      catch (NoDataFoundException ndfe) 
      { 
       //it fails so try different data type 
       try 
       { 
        CompoundGraph c = new CompoundGraph(search); 
       }     
       catch(NoDataFoundException ndfe) 
       { 
        //failed so try final type 
        try 
        { 
         BatchGraph b = new BatchGraph(search); 
        } 
        catch(NoDataFoundException ndfe) 
        { 
         MessageBox.Show("Data could not be linked to a particular search") 
        } 
       } 
      } 
     } 
+2

,将“使用控制流异常”被调用,通常不是一个好主意,或者实际上的最佳做法 – 2011-04-28 09:28:16

+0

正如Mitch所说,如果没有找到搜索结果,返回某种形式的结果并将结果用于流而不是抛出异常可能更好。 – Kane 2011-04-28 09:30:25

回答

4

,将工作,但它在两个方面是丑陋:

  • 感觉就像代码重复是一个糟糕的主意......你可以有某种形式的List<T>,例如List<Func<string, object>>并依次尝试每个工厂代表?
  • 如果找不到数据是合理的,则不应该是例外。考虑编写一个工厂方法而不是构造函数,如果没有找到数据,则返回null ...或者使用out参数和bool返回值(或者可能只是元组返回值)返回TryGetData。处理这个例外流程对我来说并不合适。
+0

+1:“如果找不到数据是合理的,那么它不应该是一个例外。考虑写一个工厂方法”[或类] ;-) – corlettk 2011-04-28 09:33:35

0

除了比你应该更频繁地抛出异常,它看起来像你的搜索构造函数可能会做更多的工作比它应该。我希望所有实例都使用光构造函数实例化,然后让他们做实际工作的时候被调用的方法,如:

// initialize graph 
IGraph p = new ParentGraph(); 

// get the results (although count may be zero) 
IEnumerable<Result> results = p.GetResults(search); // never throws an exception 

常见的接口看起来是这样的:

interface IGraph 
{ 
    IEnumerable<Result> GetResults(string search); 
} 

如果你所有的图实例实施IGRAPH,你可以使用它们像这样:

IEnumerable<IGraph> knownGraphs = new IGraph[] 
{ 
    new ParentGraph(), 
    new CompoundGraph(), 
    ... 
} 

// get results from the first graph which can give them 
foreach (IGraph graph in knownGraphs) 
{ 
    List<Result> results = graph.GetResults(search).ToList() 
    if (results.Count > 0) 
     return results; 
}