开发者

Should 'if' statement always have an 'else' clause? [closed]

开发者 https://www.devze.com 2022-12-12 19:01 出处:网络
Closed. This question is opinion-based. It is not currently accepting answers. 开发者_运维问答 Want to improve this question? Update the question so it can be answered with facts and citati
Closed. This question is opinion-based. It is not currently accepting answers.
开发者_运维问答

Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.

Closed 9 years ago.

Improve this question

This may be a religious argument, but it has been debated ad-nauseum here at my work whether all IF statements should include an ELSE clause - even if the ELSE clause only contains a comment stating that it was 'intentionally left blank'.

I have heard arguments for both sides: The 'For' camp - ensures that the codes has actually addressed whether the condition requires an ELSE clause The 'Against' camp - code is harder to read, adds too much noise

I am interested in any other points of view as I have to resolve this debate with an answer that would satisfy both parties.

Thank you for your help.

BTW: I did search StackOverflow for an answer to this and was unable to find one. If there is one, just include a link to it and close. Thanks.


Seems like useless typing to me... and a possible cause for confusion. If you don't need it, don't put it!


No. If you don't need to run any code on the else side, you don't need an else clause.


It is clear by the responses here that no one feels an unused else is needed. I have never heard nor read of such a thing. The more important issue before you is dealing with co-workers/developers who somehow believe adamantly that this is how If Then is to be used.

It sounds like you are not the senior person in this scenario so you cannot simply decree it to be so. I suggest asking the "empty else" parties to show where such a process is suggested in a book (blogs don't count) about development. Better yet, in 3 books about development. I have read my share of programming books across programming languages since 1982 and I have never seen such a suggestion.

This way you are not telling them that they are wrong which they could take personally. Instead you are willing to accept such a position but would like to see some documentation. The onus is on them to find the proof. Either they find it or they are left to argue that every programming book ever written is wrong while only they are right.

Good luck.


The golden rule: put it in if it makes your code clearer and easier to understand, and leave it out otherwise. An experienced programmer will be able to make these judgements on a case-by-case basis.


Are you talking about Algol-derived languages?

In Lisp, I'd say yes: every IF should have an else-clause. Otherwise, you should be using WHEN.


As you say, this may be a question of style, but I would not dream of putting in empty else-blocks in my code just because "every if-block should have one". In my opinion, it adds nothing else than some more characters in the code and one more point (of very little value) to spend time on during code reviews.


Requiring an else stinks. Use it when needed. All programmers understand the construct and the implication of a missing else. It's like a pointless comment that echoes the code. It's plain daft IMO.


I tend to use "early if" statements as means of reducing the level of nested braces (or indentation in Python) like so:

if (inParam == null) {
  return;
}

if (inParam.Value < 0) {
  throw new ArgumentException(...,...);
}
// Else ... from here on my if statements are simpler since I got here.

Of course, .Net 4.0 now has code contracts, which is great! But, most languages do not have that just yet, so "early ifs" (for the lack of better term) are great precisely because they eliminate a number of else clauses and nested ifs. I do not think it is beneficial to have an else clause in high-level languages ... heck, even in assembly! The idea is: if you checked and did not jump, then the condition was false and we can carry on. Makes logical sense to me ...

EDIT: Check out this article as well to see why else clauses are not of much help: http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html


"ensures that the codes has actually addressed whether the condition requires an ELSE clause"

This is no more true than requiring a catch clause in every method ensures that all possible exceptions has been properly handled.


No. Guard conditions are a great example. You could nest the rest of the method logic in else clauses but it could get ugly really quickly.


Having an "else" with just an empty line of a code comment can usually mean the developer thought-through the condition and has a better idea of what execution path is actually taken at a given time. All recent compilers will remove the "else" and the comment, so you are not slowing software execution.

Unless I am reading the other responses incorrectly, it looks like most folks are objecting to the time it takes to declare their thoughts in the code and would rather just do it.


SQL Server 2000, 2005 at least.

IF 1 = 1
BEGIN
    PRINT 'doing something productive'
END
ELSE
BEGIN
    --Just sitting here
END


Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'END'.

You have to have a meaningful statement, which means a dummy assign or return data to client. I suppose I could use WAITFOR DELAY...


Haskell's if is always ternary. So else is mandatory.


if (thereIsSomeThingToDoInTheElse)
{
    putAnElseClause();
}
else
{
    // intentionally left blank
}


If your code is complex enough that this becomes an issue, you should probably be rethinking your approach to the problem. Break what you're doing down into smaller simpler functions where it should be unbelievably obvious what the if statements are doing.

If you can't break it down into smaller functions, or you find yourself nesting more than one if statement inside another, Using if statements for your conditional logic are probably not a good fit. Consider switches, lookup tables (if the only difference between your conditions is the value of some constant), or decision tables instead.

If you've already done all this, then you are quibbling over something so unbelievably trivial it's hardly worth your time to argue it.


One of the few possible situations where this might be a good idea is where you have several nested if statements, but fewer else clauses. The language will specify which if the else matches, but this may not always be clear to the reader. Of course, where you put content in curly brackets, nesting will be obvious, so there's no ambiguity. This make this a bit of an artificial case, but still possibly worth mentioning. Also, if your code is this complicated, there's probably a clearer way of writing it.


There are situations where using an optional syntax element when not required can improve readability or prevent future errors. A typical case are the brackets around one-sentence conditionals:

Doing

if(foo){
    bar
}

instead of

if(foo)
    bar

could eventually prevent

if(foo)
    bar
    dot

I can't really think of any language I know where omitting an unnecessary else can lead to potential errors :-?


there are a lot of "words" telling you the way to programming such as DRY

in this case i'd use YAGNI.. you aint gonna need it..

so following this you shouldn't write the else.

anyhow in my opinion it makes it harder to read and understand the code.. the more you write the harder to understand the code is

edit: here are the links you requested: http://en.wikipedia.org/wiki/YAGNI http://en.wikipedia.org/wiki/Don%27t_repeat_yourself

0

精彩评论

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

关注公众号