Agile & Code Quality & Languages & Scala 16 Oct 2008 07:15 am

Rules of structured programming and Scala

Recently I have been reading “Clean Code A Handbook of Agile Software Craftsmanship” by Robert C. Martin. I was originally inspired to read this book after attending a talk given by Robert Martin at JAOO earlier this year in Brisbane where he talked about “Clean Code”.

With my current focus being on Scala, I find myself constantly thinking about some of the opinions and ideas expressed in the book in the context of the Scala Language.

While discussing techniques defining functions in “Clean Code”, Robert Martin refers to Edsger Dijkstra’s rules of structured programming.

Dijkstra said that every function, and every block within a function, should have one entry and one exit. Following these rules means that there should only be one return statement in a function, no break or continue statements in a loop, and never, ever, any goto statements.

… an excerpt from “Clean Code A Handbook of Agile Software Craftsmanship” by Robert C. Martin.

Why does this make me think of Scala? While the Scala language has both the for and while control structures built-in, the implementers of the language have chosen not to include the break or continue commands as part of the language.

I think it is a brave decisions for language designers to make the decision to exclude such entrenched concepts as the break or the continue command from a language. This exclusion will force coders to think a little harder about the best way to describe their intent in code. I think Scala have got it right.

One Response to “Rules of structured programming and Scala”

  1. on 18 Oct 2008 at 12:44 am 1.James Iry said …

    I think the “only one return” notion is a bit over strong for Scala, depending on what you mean by a return. Taken literally it might mean I can’t write this

    def evenOdd(n:Int) = if(n%2==0) “even” else “odd”

    Instead I would have to write this

    def evenOdd(n:Int) = {val result = if(n%2==0) “even” else “odd”; result}

    In my mind the later is less significantly harder to read. Similar things go for pattern matching where you often write def foo(x:Bar) = x match {case …

    A better guideline for Scala is “avoid the ‘return’ keyword.” It’s usually (though not always) a code smell in Scala to have explicit ‘return.’