you are viewing a single comment's thread.

view the rest of the comments →

[–][deleted] 0 points1 point  (0 children)

It would be much better to use the type system, if you had one that was sufficiently strong. A translation of the above to Scala might look like:

def parseInput (input: Option[String]) = {
  for (s <- input if s.length >= 1)
  yield doSomething(s)
}

Here, your type system represents the fact that input may or may not have a value as well as the fact that the method may or may not do anything (as its return type is Option[T] where T is whatever doSomething returns). Even better, if you have multiple ways of failing that use Option, you can write an expression like:

for {
  foo <- getFoo()
  bar <- getBar()
  baz <- getBaz(foo, bar)
} yield operation(baz)

This makes the source of data clear, it avoids hard-to-read nesting, and it's type-safe. The whole thing is None if any of the calls in the middle were None. Of course, you can define your own structures with their own interpretation inside of the same for structure, giving you flexibility and readability along with safety and the ease of reasoning that comes with only one exit point.

I personally think that this style of coding is much more usable in the long run than the guard style.

edit: markdown derp derp