Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

I am reading Learn Python the Hard Way by Zed Shaw. In this lesson he writes: "Every if-statement must have an else."

What are the benefits of ending every if-statement with an else? Are there any legitimate reasons not to end an if-statement with an else?

share|improve this question
    
I don't work in Python, but I suspect that may have something to do with the way indendation controls scope (as I understand it). He might be saying that you must ALWAYS have an else to make the end of the condition block more obvious, even if the else does nothing. I've never heard such a recommendation for other languages, and to say you must do it seems very excessive. –  FrustratedWithFormsDesigner Mar 22 '12 at 20:17
4  
IMO an empty else doesn't make any sense, and not every if needs to do something useful in the else branch. An else that should never be reached is suspicious in the first place, because why would I write an if when I'm sure that it will always be true? Maybe there a special reasons that only apply to python, though. –  user281377 Mar 22 '12 at 20:18
    
@ammoQ I'm with you, and there's nothing Python-specific that comes to mind. This rule seems bullshit, although the context makes it less of an atrocity and more of a seemingly pointless rule. –  delnan Mar 22 '12 at 20:20
1  
By the way, the recommendation "Do not use a debugger", given on the same page, is questionable at best. I would take anything he writes with a grain of salt. –  user281377 Mar 22 '12 at 20:21
4  
The benefit is that by doing completely pointless things you are learning Python the hard way, as promised. –  psr Mar 22 '12 at 20:55
add comment

4 Answers

up vote 10 down vote accepted

Directly under the list of rules is the following statement:

Never be a slave to the rules in real life. For training purposes you need to follow these rules to make your mind strong, but in real life sometimes these rules are just stupid. If you think a rule is stupid, try not using it.

It looks like the rules are setup to be overly cautious because the target audience is just starting. By doing this, it forces the student to form good habits when writing future code. If you are able to explain why you no longer think the rule is worth following (and support it with a good reason), you are already thinking deeply on the issue. This means you have weighed the options and decided to accept what risk there might be. You are also less likely to make a mistake the rule would have prevented if you have spent that much time thinking about the rule.

share|improve this answer
1  
Since this rule hardly ever makes sense, I see no point in teaching it to students. Or anyone else, for the matter. Writing senseless code isn't a good habit, it's either sluttery or (like in this case) superstition. –  user281377 Mar 22 '12 at 20:42
1  
@ammoQ: While I agree that the rule has no place in the real world and I wouldn't have put it in a book, I can see it benefiting a new student some. It causes your code to fail as soon as it does something you don't intend. This will prevent a new student from spending lots of time looking at the exception point when the error is caused by a logic error earlier in the code. It is also forcing the student to think about their if clauses. What is it checking? What is the opposite of that? Is there ambiguity in how the clause was written? –  unholysampler Mar 22 '12 at 21:08
    
unholysampler: I don't get your point. Sure, there are ifs that would better be asserts, so we want the code to fail. But the rule applies to each and every if, even those where evaluating the condition to false is perfectly valid and there is nothing to do in the else branch. Writing else just because the rule says so is senseless. –  user281377 Mar 22 '12 at 21:26
    
@ammoQ: The book is taking the stance that is better to know everything that is going on rather than letting examples just work. When you are just starting as a programmer, getting verification that thing you intend to not happen did not happen can help you debug code. Again, I don't support the rule or the author claim that print statements are the only way to debug code, but I can see where he is coming from given the initial mission statement. –  unholysampler Mar 22 '12 at 21:47
    
@unholysampler: I misread the book's Warning that you posted in your answer! I read "sometimes the rules are stupid," instead of "these rules are stupid." That changes everything. Thanks for being more attentive than me. Sheepishly leaves room. –  Brian Dant Mar 22 '12 at 22:41
show 1 more comment

I have worked with code that has a case that "absolutely won't happen". And then it happens... Even if the else clause logs the problem it makes sure that you'll find it when it bites you later on.

I don't know much about code coverage, but I would think you would get better results if all paths are covered.

share|improve this answer
2  
If the else cannot happen (= the conidition must always be true), what's the point in having a branch? Just drop the if, and assert condition to get the same sanity check without confusing readers. –  delnan Mar 22 '12 at 20:19
    
What does code coverage have to do with this? It's not about unit testing. –  Michael K Mar 22 '12 at 20:19
    
@delnan - "logical" can never happen is different from "business" can never happen. There is a lot of - that never happens - assumptions living in code! –  Martin Beckett Mar 22 '12 at 20:24
1  
@MartinBeckett Yeah, but these are better handled with an assertion or something, not by a pointless if. There are numerous ways to get that security - if must_always_be_true { half_of_method() } else { cannot_happen(); } is one way to do it, but as others have argued, you should do early return/throw instead. I'd go as far as claiming it's the only sensible variant (most of StackExchange seems to agree) - if you need a dozen ifs to get to the actual code, you got way too much (pointless too!) indentation. –  delnan Mar 22 '12 at 20:31
add comment

I think it depends on what your purpose is. If you want for example to error check a function you dont need an else-statement:

    def foo(bar):
        if(bar<0 or bar>10) or not isinstance(bar,int):
            return -1
        print "successfull"
        print bar

But if you something more complex like if that... do this this this... and else... do this this this... then you should do "else" for readability, even if it is not really necessary.

share|improve this answer
1  
I think you made a typo in your answer bar can never be less than 0 and greater than 10 –  Ryathal Mar 22 '12 at 20:22
    
@Ryathal sorry but I don't know what a typo is, can you tell me? –  Bughead Mar 22 '12 at 20:26
    
@Ryathal now i got it you meant the "and" statement and thus my typography. I thought you meant something like "if bar not in range(0,10)" ... –  Bughead Mar 22 '12 at 20:33
    
@xMRW: en.wiktionary.org/wiki/typo, you probably meant or instead of and. –  Benjamin Bannier Mar 22 '12 at 20:35
add comment

I think he's trying to demonstrate something about flow control. What exactly he's trying to demonstrate is anyone's guess, but I think he's trying to make you stop and think about what the "path not taken" in any if-statement would do. Presumably he's run into a problem in the past where this type of thinking would have proven useful.

This type of rule is just way to absurd to apply in real life though.

share|improve this answer
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.