PBP: 081 Linear Coding

This suggestion seems oddly worded to me, although I’m not sure I can think of a better one.  The book says, “Reject as many iterations as possible, as early as possible.”  Luckily, it goes on to explain what this means, as that isn’t – at least to  me – terribly clear.  It winds up being an extension of “coding in paragraphs” and is more about how to organize your code than how to format it.  I think I agree with this and do it all the time, despite having had many college professors claim it is the root of all evil.

The goal of this practice is to have you process your data “in paragraphs” much as you lay out the code, and to handle exceptions early.  This means rather than gathering up a bunch of data, then doing a bunch of validation, and then doing a bunch of work, you build one item and verify it right away.  Only after all the items are verified, do you do your work.

There’s several advantages to this.  One is that you can skip work of gathering and verifying data if earlier parts of the data isn’t available or isn’t usable.  No reason to scrape all that stuff into a pile if you’re not going to use it.  Another is that if how you get the data changes, all the things related to gathering and verifying that data are together, rather than in separate blocks.

Some of the professors I had in college hated functions with multiple exit points.  This scheme would have made them furious, because you can escape out all over the place, and skip parts of the function.  I say screw ’em.  I said it then, too.  They’re wrong.  It does make writing tests to test full code coverage more difficult, as you have to work out ways to trigger every exit in the processing.  It shouldn’t be any different than handling each case as separate functions, though.

I think of this kind of processing as “running the gauntlet”.  Your code picks up each item it needs and verifies it.  If it gets through all the verifications without aborting, then the data is right and you can do  whatever work you needed.  I do this naturally, and find it a good suggestion.

It also fits well with exception based code, as you don’t always have to return an error – you just die.  Someone had better catch the error, or it’ll be the end of your program, but if it’s that bad a problem, maybe that’s okay.

Leave a Reply