Chapter 3. Modicum of style—coding conventions

 

In this chapter

  • The dangers of dragging old coding conventions into Scala
  • Working with end-of-line inference
  • Avoiding dangerous names for variables
  • Ensuring correct behavior with annotations

This chapter presents style suggestions that will help you avoid compiler or runtime errors. Style issues are usually a “holy war” among developers, who each has her own opinions. But there are certain things that Scala allows from a style perspective that can cause logic or runtime issues in your programs. This chapter doesn’t try to proselytize you into whether you should place spaces between parenthesis or what the best number of spaces for indentation is. This chapter merely presents a few styles that will cause real issues in Scala, and why you should modify your preferred style accordingly, if needed.

We discuss why placing opening braces for block expressions can convey different meanings to the compiler. Operator notation can cause issues if the compiler can’t tell where a line ends. Also, when naming variables in Scala, there are some names that are syntactically valid but will cause compiler or runtime errors. Finally, we discuss the benefits of compile-time warnings and how you can use annotations to increase the helpfulness of the Scala compiler. Let’s start by looking at some common coding conventions.

3.1. Avoid coding conventions from other languages

3.2. Dangling operators and parenthetical expressions

3.3. Use meaningful variable names

3.4. Always mark overridden methods

3.5. Annotate for expected optimizations

3.6. Summary