Scala coding styles and conventions?

"If the method grows it becomes very painful to read the code". I think part of the answer is that methods should not grow. The functional programing style is to have many small methods.The calculate method is already on the large side.

To answer the more general questions about style guides for Scala programing: Here's a representative example.


The particular example that you quote may look complex because it is using a cache to memoize the results. If you remove the memoization, the method reduce to:

def calculate(s: String): Int = {
    val acc = new ChecksumAccumulator
    for (c <- s)
        acc.add(c.toByte)
    acc.checksum()
}

which I think, is not complex at all.


Here is a link to the Scala Style Guide.


The Curly Braces section says:

Curly-Braces:

Curly-braces should be omitted in cases where the control structure represents a pure- functional operation and all branches of the control structure (relevant to if/else) are single-line expressions. Remember the following guidelines:

  • if - Omit braces if you have an else clause. Otherwise, surround the contents with curly braces even if the contents are only a single line.

  • while - Never omit braces (while cannot be used in a pure-functional manner).

  • for - Omit braces if you have a yield clause. Otherwise, surround the contents with curly-braces, even if the contents are only a single line.

  • case - Omit braces if the case expression ts on a single line. Otherwise, use curly braces for clarity (even though they are not required by the parser).

    val news = if (foo)
      goodNews()
    else
      badNews()
    
    if (foo) {
      println("foo was true")
    }
    
    news match {
      case "good" => println("Good news!")
      case "bad" => println("Bad news!")
    }
    

I wish people followed this style guide :(


Please note that I don't agree with "Omit braces if if has an else clause" part. I'd much prefer to see the code like this:

def calculate(s: String): Int = {
  if (cache.contains(s)) {
    cache(s)
  } else {
    val acc = new ChecksumAccumulator
    for (c <- s) {
      acc.add(c.toByte)
    }
    val cs = acc.checksum()
    cache += (s -> cs)
    cs
  }
}

The official guide is at https://docs.scala-lang.org/style/ (adopted from now removed http://davetron5000.github.io/scala-style/index.html, see Web Archive).

Tags:

Scala