Forcing indentation: yes, it is a good thing

At work I’m trying to get some of my colleagues to give Python a try. Every time I bring up the subject I have to hear things like but there are not brackets … and what’s up with the forced indentation?

Needless to say I always reply that indentation is good as the end result is usually code that is easier to read and that once you have blocks of code defined by their indentation level you don’t need brackets anymore. But no, they will have none of that.

At work I’m currently writing (more like learning how to) code in C#. I’ve recently posted on C# scope oddities that puzzled me and here I am writing about C# (although this rant applies to other languages as well) again.

Assume for a second that you had written a piece of code along the lines of

if(condition_1_is_met)

if(condition_2_is_met) {

// do your stuff here

}

else {

// handle condition_1_not_met here? Wrong! condition_2_not_met is handled here!

}

Unfortunately, for me and you, this doesn’t work. The else clause is actually, possibly due to design reasons, associated to the second if clause (condition_2_is_met) and not to the first one. Oh yes, I can already hear you saying but you should group condition_1 and condition_2!!! And I could almost agree to that if that didn’t require an extra if in case we wanted to handle the else clauses independently. So, to actually be able to attach an else clause to the first if clause we need an extra else that does nothing as you can see below:

if(condition_1_is_met)

if(condition_2_is_met) {

// do your stuff here

} else {

// here’s where you handle condition_2_not_met

}

else {

// handle condition_1_not_met here

}

That is just fine and possibly makes the whole code clearer (?) Unless you don’t care for having an else clause attached to the second if …

And in comes Python with it’s forced indentation:

if condition_1_is_met:

if condition_2_is_met:

# do your stuff in here

else:

# handle condition_1_not_met here

How nice is that then? Indentation there is not only telling you (when you read the code) to which if clause the else clause is attached to but also is telling the compiler the same thing. No extra empty else clauses, etc. Just indentation guiding the flow … as it should be.

I rest my case.

Post a Comment

Your email is never published nor shared. Required fields are marked *