Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
542 views
in Technique[技术] by (71.8m points)

c# - In an If-Else Statement for a method return, should an Else be explicitly stated if it can instead be implicitly followed?

I have a method that checks certain things and returns a Boolean based on those checks. It involves a single branching If section that checks about 5 conditions in sequence. If any of those conditions return true, then the method will return true;. If none of the conditions return true, then the method will return false;. Since the code after the If section will only run if none of the conditions are true, then that code is logically identical to including an actual Else statement.

So is it a better idea to actually write in the Else statement for this kind of situation?

EDIT

It turns out that I needed information on which condition actually tripped the "true" for some of these, so I changed the method to return an int, with -1 representing the "false" situation. The logic still remains, if none of the conditions are true, it'll return -1. So, I no longer have the condensable option of return (cond1 || cond2 || cond3 || cond4 || cond5);, but I thank everyone for that suggestion too, since I had indeed not thought about it (primarily because cond3 is a very complex condition involving checking for intersection in the midpoints of two pairs of DateTime objects, so it would look ugly). While the nature of the method has changed, the nature of this question has not and all answers are still basically applicable...

The code is currently, to paraphrase it and cut out all the extraneous code that defines cond1 thru cond5...

if (cond1) { return 1; }
else if (cond2) { return 2; }
else if (cond3) { return 3; }
else if (cond4) { return 4; }
else if (cond5) { return 5; }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's really a matter of style and what you (and those you work with) find to be clearer. In general, I personally find the structure:

if( a )
   someResult = doSomething();
else if( b )
   someResult = doSomethingElse();
else
   someResult = doSomethingAnyways();

return someResult;

clearer than:

if( a )
    return doSomething();
if( b )
    return doSomethingElse();
return doSomethingAnyways();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...