开发者

more short code about if statement

i wanted to try the following code:

//all arrays are List<T> type.
if (m.terms[0] != null && m.terms[0].labels != null && m.terms[0].labels[0].title == "Part-of-speech")
{
    result = true; 
}

but it occured runtime error occasionly in following situation

i. m.terms == null

ii. m.terms != null, but m.terms[0] does not intialized.

iii. m.terms != null, and m.terms[0] has been exist but m.terms[0].label doe开发者_JAVA技巧s not initialized.

...

so i did modify it to like this:

if (m.terms[0] != null)
{
    if (m.terms[0].labels != null)
    {
        if (m.terms[0].labels[0].title == "Part-of-speech") { result = true; }
    }
}

is it the best way?


&& is a short circuiting operator, so the first way you wrote it and the second way will be functionally equivalent.

if (a && b && c)
{
    // work 
}

b will only be evaluated if a returns true. (Same goes for c).

In your code, checking m.terms[0].labels will not be a problem because you would have short-circuited out of the expression if m.terms[0] had been null.

To completely cover yourself, you'd want to possibly add checks for m and m.terms, however.

m != null && m.terms != null && m.terms.Count > 0 && m.terms[0] != null ...

As it evaluates from left to right, it will break on the first condition that doesn't pass and the rest will go unchecked.


int index = 0;
int labelIndex = 0;
string titleToCheck = "Part-of-speech";

if (m != null && m.terms != null && m.terms.Count > index)// or m.Length...
{
    if (m.terms[index] != null && m.terms[index].labels != null &&
        m.terms[index].labels.Count > labelIndex)
    {
        if (m.terms[index].labels[labelIndex].title == titleToCheck)
        {
            result = true; 
        }
    }
}


This is all about readability. C# uses Short-circuit evaluation so in functionality there is no difference.


try this

if (m!=null && m.terms!= null && m.terms[0].labels!=null && m.terms[0].labels[0].title!=null && m.terms[0].labels[0].title == "Part-of-speech")


Yes, it would be better to split off each null check into a separate if statement.

The reason is that the second and third conditions require the first to not be null. If the first is null, then the second and third conditions will in turn throw errors because their parent is null yet is trying to be accessed.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜