Chapter 24. Best Practices
When I first came to Scala from Java in 2010, I was happy with the small things, such as eliminating a lot of ;
, ()
, and {}
characters, and working with a less verbose language that reminded me of Ruby. Not knowing much about the history of programming languages, I thought of Scala as being “Ruby with types,” and all of 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 is quoted in the book Clean Code by Robert C. Martin (Prentice Hall), I wanted to write code that “makes it look like the language was made for the problem,” so I learned the collections classes and their methods, for
expressions, match
expressions, and modular development. 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 jumping into the recipes in this chapter, here’s a short summary of the best Scala practices I know.
At the application level:
-
As Martin Odersky has stated, write functions for the logic, and create objects for the modularity.
-
When you write functions, try to write as many of them as you can as pure functions. Following the 80/20 rule, this is like writing 80% of your application as pure functions, with a thin layer of other code on top of those functions for things like I/O. As someone once wrote, it’s like putting a thin layer of impure icing ...
Get Scala Cookbook, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.