<commit_before># Scala Programming Best Practices

![Scala Logo](static/scala-logo.png "Scala")

## Index

* [Introduction](#introduction)
* [Formatting](#formatting)
* [Types and Generics](#types-and-generics)
* [Collections](#collections)
* [Concurrency](#concurrency)
* [Control structures](#control-structures)
* [Functional programming](#functional-programming)
* [Object oriented programming](#object-oriented-programming)
* [Error handling](#error-handling)
* [References](#references)

### Introduction

This is not an introduction to Scala we assume the reader is familiar with the language. Some resources for learning Scala are:

[ScalaByExample](http://www.scala-lang.org/docu/files/ScalaByExample.pdf)

[A Scalable Language](https://www.artima.com/pins1ed/index.html#TOC)

This is a living document that will change to reflect our current “best practices,” but its core ideas are unlikely to change: Always favor readability write generic code but not at the expensive of clarity take advantage of simple language features that afford great power but avoid the esoteric ones (especially in the type system). Above all, be always aware of the trade offs you make. A sophisticated language requires a complex implementation, and complexity begets complexity: of reasoning, of semantics, of interaction between features, and of the understanding of your collaborators. Thus complexity is the tax of sophistication — you must always ensure that its utility exceeds its cost.

**[Index](#index)**

### Formatting

Style cannot be inherently good or bad and almost everybody differs in personal preference. However the consistent application of the same formatting rules will almost always enhance readability. A reader already familiar with a particular style does not have to grasp yet another set of local conventions, or decipher yet another corner of the language grammar.

This is of particular importance to Scala, as its grammar has a high degree of overlap.

We adhere to the [Scala style] (http://docs.scala-lang.org/style/)  guide plus the following rules

#### Whitespace
Indent by two spaces. Try to avoid lines greater than 100 columns in length. Use one blank line between method, class, and object definitions

#### Naming
_Use short names for small scopes_

    is, js and ks are all but expected in loops.

_Use longer names for larger scopes_

    external APIs should have longer and explanatory names that confer meaning. Future.collect not Future.all

_Use common abbreviations but eschew esoteric ones_

    Everyone knows ok, err or defn whereas sfri is not so common.

_Don't rebind names for different uses_

    Use vals

_Avoid using s to overload reserved names_

    typ instead of `type`

_Use active names for operations with side effects_

    user.activate() not user.setActive()

_Use descriptive names for methods that return values_

    src.isDefined not src.defined

_Do not prefix getters with get_

    As per the previous rule, it is redundant: site.count not site.getCount

_Do not repeat names that are already encapsulated in package or object name_

    Prefer:

```scala
object User {
  def get(id: Int): Option[User]
}
```

    to:

```scala
object User {
  def getUser(id: Int): Option[User]
}
```

_They are redundant in use_

    User.getUser provides no more information than User.get.

#### Imports

_Sort import lines alphabetically_

    This makes it easy to examine visually, and is simple to automate.

_Use braces when importing several names from a package_

    import com.beeva.concurrent.{Broker, Offer}

_Use wildcards when more than six names are imported_

    e.g.: import com.beeva.concurrent._
    Don't apply this blindly: some packages export too many names_

_When using collections, qualify names by importing scala.collection.immutable and/or scala.collection.mutable_

    Mutable and immutable collections have dual names.
    Qualifiying the names makes is obvious to the reader which variant is being used (e.g. "immutable.Map")

_Do not use relative imports from other packages_

    Avoid
    import com.beeva
    import concurrent
    in favor of the unambiguous
    import com.beeva.concurrent

_Put imports at the top of the file_

    The reader can refer to all imports in one place.

#### Braces

Braces are used to create compound expressions (they serve other uses in the “module language”), where the value of the compound expression is the last expression in the list. Avoid using braces for simple expressions.

Write

```scala
def square(x: Int) = x*x
```
but not

```scala
def square(x: Int) = {
  x * x
}
```

even though it may be tempting to distinguish the method body syntactically. The first alternative has less clutter and is easier to read. Avoid syntactical ceremony unless it clarifies.

#### Pattern matching

Use pattern matching directly in function definitions whenever applicable.

Instead of

```scala
list map { item =>
  item match {
    case Some(x) => x
    case None => default
  }
}
```

collapse the match

```scala<commit_msg>Fixed code blocks<commit_after># Scala Programming Best Practices

![Scala Logo](static/scala-logo.png "Scala")

## Index

* [Introduction](#introduction)
* [Formatting](#formatting)
* [Types and Generics](#types-and-generics)
* [Collections](#collections)
* [Concurrency](#concurrency)
* [Control structures](#control-structures)
* [Functional programming](#functional-programming)
* [Object oriented programming](#object-oriented-programming)
* [Error handling](#error-handling)
* [References](#references)

### Introduction

This is not an introduction to Scala we assume the reader is familiar with the language. Some resources for learning Scala are:

[ScalaByExample](http://www.scala-lang.org/docu/files/ScalaByExample.pdf)

[A Scalable Language](https://www.artima.com/pins1ed/index.html#TOC)

This is a living document that will change to reflect our current “best practices,” but its core ideas are unlikely to change: Always favor readability write generic code but not at the expensive of clarity take advantage of simple language features that afford great power but avoid the esoteric ones (especially in the type system). Above all, be always aware of the trade offs you make. A sophisticated language requires a complex implementation, and complexity begets complexity: of reasoning, of semantics, of interaction between features, and of the understanding of your collaborators. Thus complexity is the tax of sophistication — you must always ensure that its utility exceeds its cost.

**[Index](#index)**

### Formatting

Style cannot be inherently good or bad and almost everybody differs in personal preference. However the consistent application of the same formatting rules will almost always enhance readability. A reader already familiar with a particular style does not have to grasp yet another set of local conventions, or decipher yet another corner of the language grammar.

This is of particular importance to Scala, as its grammar has a high degree of overlap.

We adhere to the [Scala style] (http://docs.scala-lang.org/style/)  guide plus the following rules

#### Whitespace
Indent by two spaces. Try to avoid lines greater than 100 columns in length. Use one blank line between method, class, and object definitions

#### Naming
_Use short names for small scopes_

    is, js and ks are all but expected in loops.

_Use longer names for larger scopes_

    external APIs should have longer and explanatory names that confer meaning. Future.collect not Future.all

_Use common abbreviations but eschew esoteric ones_

    Everyone knows ok, err or defn whereas sfri is not so common.

_Don't rebind names for different uses_

    Use vals

_Avoid using s to overload reserved names_

    typ instead of `type`

_Use active names for operations with side effects_

    user.activate() not user.setActive()

_Use descriptive names for methods that return values_

    src.isDefined not src.defined

_Do not prefix getters with get_

    As per the previous rule, it is redundant: site.count not site.getCount

_Do not repeat names that are already encapsulated in package or object name_

    Prefer:

```scala
object User {
  def get(id: Int): Option[User]
}
```

    to:

```scala
object User {
  def getUser(id: Int): Option[User]
}
```

_They are redundant in use_

    User.getUser provides no more information than User.get.

#### Imports

_Sort import lines alphabetically_

    This makes it easy to examine visually, and is simple to automate.

_Use braces when importing several names from a package_

    import com.beeva.concurrent.{Broker, Offer}

_Use wildcards when more than six names are imported_

    e.g.: import com.beeva.concurrent._
    Don't apply this blindly: some packages export too many names_

_When using collections, qualify names by importing scala.collection.immutable and/or scala.collection.mutable_

    Mutable and immutable collections have dual names.
    Qualifiying the names makes is obvious to the reader which variant is being used (e.g. "immutable.Map")

_Do not use relative imports from other packages_

Avoid

    import com.beeva
    import concurrent

in favor of the unambiguous

    import com.beeva.concurrent

_Put imports at the top of the file_

    The reader can refer to all imports in one place.

#### Braces

Braces are used to create compound expressions (they serve other uses in the “module language”), where the value of the compound expression is the last expression in the list. Avoid using braces for simple expressions.

Write

```scala
def square(x: Int) = x*x
```

but not

```scala
def square(x: Int) = {
  x * x
}
```

even though it may be tempting to distinguish the method body syntactically. The first alternative has less clutter and is easier to read. Avoid syntactical ceremony unless it clarifies.

#### Pattern matching

Use pattern matching directly in function definitions whenever applicable.

Instead of

```scala
list map { item =>
  item match {
    case Some(x) => x
    case None => default
  }
}
```

collapse the match

```scala
{'fraction_non_alphanumeric': 0.06553157790536528, 'fraction_numerical': 0.0007919223916056226, 'mean_word_length': 4.28676085818943, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 9, 'https://': 2, 'lorem ipsum': 0, 'www.': 4, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5180766', 'n_tokens_mistral': 2764, 'n_tokens_neox': 2573, 'n_words': 1321}