2011-06-20 33 views
2

情况:我在代码中遇到很多检查。我想知道一种我可以减少它们的方法。如何检查干草堆中针头的零位和空串?

if(needle!=null && haystack!=null) 
{ 
    if(needle.length()==0) 
    return true; 
    else 
    { 
    if(haystack.length()==0) 
    return false; 
    else 
    { 
    // Do 2 for loops to check character by character comparison in a substring 
    } 
} 

} 
else 
return false; 

回答

5

也许不同的代码风格会提高代码的可读性,并减少嵌套if报表金额为所有检查:

if (needle == null || haystack == null || haystack.isEmpty()) 
    return false; 

if (needle.isEmpty()) 
    return true; 

// compare strings here and return result. 
+0

谢谢史蒂夫! – phoenix

0

您可以创建一个包装类的字符串,然后添加像isValid()的给他们一个函数来检查,如果长度== 0,使用Null Object总是对的isValid返回false()来消除空检查。

如果你可以创建你告诉做什么,而不是传递的是必须在你的代码空检查串类,你会得到更多resuseable结果:

class Haystack { 
    private static final Haystack NULL_HAYSTACK = new Haystack(""); 
    private final String value; 

    public Haystack(String value) { 
     this.value = value; 
    } 

    public boolean containsNeedle(String needle) { 
     return needle != null && value.contains(needle); 
    } 
} 
0

你可以巩固逻辑到单个StringFunctions类中的单个方法,并更新用法以在遇到它们时使用常用方法。