Scala best practices (idioms) (from the Scala Cookbook)

This is an excerpt from the Scala Cookbook (partially modified for the internet). This is the introduction to Chapter 20, Idioms (Scala best practices).

When I first came to Scala from Java, I was happy with the small things, including eliminating a lot of ;, (), and {} characters, and writing more concise, Ruby-like code. These were nice little wins that made for “a better Java.”

Over time, I wanted to add more to my repertoire and use Scala the way it’s intended to be used. As Ward Cunningham said in the book, Clean Code (Prentice Hall), I wanted to write code that “makes it look like the language was made for the problem.” That’s what this chapter is about—trying to share some of the best practices of Scala programming so you can write code in “the Scala way.”

Before digging into the recipes in this chapter, here’s a short summary of Scala’s best practices.

Application level best practices

At the application level:

  • At the big-picture, application-design level, follow the 80/20 rule, and try to write 80% of your application as pure functions, with a thin layer of other code on top of those functions for things like I/O.
  • Learn “Expression-Oriented Programming” (Recipe 20.3).
  • Use the Actor classes to implement concurrency (Chapter 13).
  • Move behavior from classes into more granular traits. This is best described in the Scala Stackable Trait pattern.

Coding level best practices

At the coding level:

  • Learn how to write pure functions. At the very least, they simplify testing.
  • Learn how to pass functions around as variables (Recipes 9.2 to 9.4).
  • Learn how to use the Scala collections API. Know the most common classes and methods (Chapter 10 and Chapter 11).
  • Prefer immutable code. Use vals and immutable collections first (Recipe 20.2).
  • Drop the null keyword from your vocabulary. Use the Option/Some/None and Try/Success/Failure classes instead (Recipe 20.6).
  • Use TDD and/or BDD testing tools like ScalaTest and specs2.

Outside the code:

  • Learn how to use the Simple Build Tool (SBT). It’s the de-facto Scala build tool (Chapter 18).
  • Keep a REPL session open while you’re coding (or use the Scala Worksheet), and constantly try small experiments (Recipes 14.1 to 14.4, and many examples throughout the book).

Other Resources

In addition to the practices shared in this chapter, I highly recommend reading Twitter’s Effective Scala document. The Twitter team has been a big user and proponent of Scala, and this document summarizes their experiences.

The Scala Style Guide is a good resource that shares examples of how to write code in the Scala “style.”