Early returns can be useful in statement-based languages like Java or C# to restructure code and eliminate nesting.
When using F# for the first time, one of the things I struggled with was the lack of early returns. The concept of an early return doesn’t make sense in an expression-based language, where we’re composing values together to produce new values rather than sequencing statements. How then do we deal with nesting in F#?
Here’s some code that looks two things up, then combines those things if they both have a value:
One level of nesting is not awful, but…
Static types can really aid in designing software, especially if your type system has good facilities for composing those types.
Let’s say we want to define a binary tree. Each node in a binary tree consists of an element and 0–2 children. Here’s how we could define a tree of integers in Haskell:
data Tree = Empty
| Node Tree Int Tree
This syntax may not be familiar, so let’s break it down. We are defining a custom data type called
| (read “or”) indicates that there are two variants. …
Software Developer at @pluralsight. Especially interested in functional programming and programming languages. Find me on twitter @justin_hewlett