This repository contains style guidelines for writing Scala code at PayPal. Here are our goals for style guides in this repository:
- Our style guidelines should be clear.
- We all should agree on our style guidelines.
- We should change this guideline as we learn and as Scala evolves.
- Keep the scalastyle-config.xml in our projects in line with this guide as much as possible.
This repository follows git-flow. If you have a new style guideline, open a pull request against develop. We'll
discuss in the PR comments. The official guidelines live in master
- Use two spaces for indentation.
- Add a newline to the end of every file.
- Use a maximum line length of 160 characters.
Use camel case for all function, class and variable names. Classes start with an upper case letter, and values and functions start with a lower case. Here are some examples:
class MyClass {
val myValue = 1
def myFunction: Int = myValue
}Use camel case for acroynms, for example, HttpUtil. For consistency, this includes class names like Ttl and Json as well as common terms such as Db and Io. Follow normal camel-casing rules.
val httpIoJsonToXmlParser = new HttpIoJsonToXmlParser()Package names should be all lowercase with no underscores.
File names for package objects must match the most specific name in the package.
For example, for the com.paypal.mypackage package object, the file
should be named mypackage.scala and the file should be structured like this:
package com.paypal
package object mypackage {
//...
}Limit the number of public methods in your class to 30.
- Prefer non-case classes when defining exceptions and errors unless you plan on pattern matching on the exception.
- If providing a cause is desirable and not mandatory then define it as an option. Note, the use of
.orNull.
class CrazyException(msg: String, cause: Option[Throwable] = None) extends Exception(msg, cause.orNull)
class SuperCrazyError(msg: String, cause: Option[Throwable] = None) extends Error(msg, cause.orNull)IntelliJ's code style configuration allows for automatic grouping of imports by namespace. We use the following ordering, which you should add to your IntelliJ configuration (found in Preferences > Code Style > Scala):
java
___blank line___
scala
___blank line___
akka
spray
all other imports
___blank line___
com.ebay
com.paypal
You should also regularly run IntelliJ's Optimize Imports (Edit > Optimize Imports) against
your code before merging with develop, to maintain import cleanliness.
Most imports in a file should go at the top, right below the package name. The
only time you should break that rule is if you import some or all names from
an object from inside a class. For example:
package mypackage
import a.b.c.d
import d.c.b.a
class MyClass {
import Utils._
import MyClassCompanion.A
}
object MyClassCompanion {
case class A()
}
object Utils {
case class Util1()
case class Util2()
}Never import anything inside of Scala's
'Predef'
object. It is automatically imported for you, so it's redundant to manually
import. IntelliJ will often try to import it, so be aware.
Use val by default. vars should be limited to local variables or private class variables. Their usage
should be well documented, including any considerations that developers must make with respect to concurrency.
One common usage of vars will be inside of Akka Actors. Here's an example of that usage:
class MyActor extends Actor {
//This is local state to the actor that represents the current sum of all integers it has received.
//It must be marked private and never accessed outside of the processing of a single message, to ensure
//that it's concurrency safe. Additionally, don't acquire a lock before you access this variable.
//Doing so might block message processing unnecessarily. If you follow all of these rules related to concurrency,
//you shouldn't need a lock anyway.
private var sum: Int = 0
override def receive: Receive {
case i: Int => sum = sum + 1
}
}Optional variable modifiers should be declared in the following order: override access (private|protected) final implicit lazy.
For example,
private implicit lazy val someSetting = ...Rules to follow for all functions:
- Always put a space after
:characters in function signatures. - Always put a space after
,in function signatures.
All public functions and methods, including those inside objects must have:
- A return type
- Scaladoc including a function overview, information on parameters, and information on the return value. See the Scaladoc section for more details.
Here is a complete example of a function inside of an object.
object MyObject {
/**
* returns the static integer 123
* @return the number 123
*/
def myFunction: Int = {
123
}
}If a function has a parameter list with fewer than 70 characters, put all parameters on the same line:
def add(a: Int, b: Int): Int = {
...
}If a function has long or complex parameter lists, follow these rules:
- Put the first parameter on the same line as the function name.
- Put the rest of the parameters each on a new line, aligned with the first parameter.
- If the function has multiple parameter lists, align the opening parenthesis with the previous one and align parameters the same as #2.
Example:
def lotsOfParams(aReallyLongParameterNameOne: Int,
aReallyLongParameterNameTwo: Int,
aReallyLongParameterNameThree: Int,
aReallyLongParameterNameFour: Int)
(implicit adder: Adder,
reader: Reader): Int = {
...
}For function names over 30 characters, try to shorten the name. If you can't, start the parameter list on the next line and indent everything 2 spaces:
def aVeryLongMethodThatShouldHaveAShorterNameIfPossible(
aParam: Int,
anotherParam: Int,
aThirdParam: Int)
(implicit iParam: Foo,
bar: Bar): String = {
...
}In all cases, the function's return type still has to be written directly following the last closing parenthesis.
When calling functions with numerous arguments, place the first parameter on the same line as the function and align the remaining parameters with the first:
fooBar(someVeryLongFieldName,
andAnotherVeryLongFieldName,
"this is a string",
3.1415)For functions with very long names, start the parameter list on the second line and indent by 2 spaces:
aMuchLongerMethodNameThatShouldProbablyBeRefactored(
aParam,
anotherParam,
aThirdParam)It's your choice whether to place closing parenthesis directly following the last parameter or on a new line (in "dangling" style).
You can do this:
aLongMethodNameThatReturnsAFuture(
aParam,
anotherParam,
aThirdParam
).map { res =>
...
}Or this:
aLongMethodNameThatReturnsAFuture(
aParam,
anotherParam,
aThirdParam).map { res =>
...
}Anonymous functions start on the same line as preceding code. Declarations
start with { (note the space before and after the {). Arguments are then
listed on the same line. A few more notes:
- Do not use braces after the argument list, just start the function body on the next line.
- Argument types are not necessary. You should use them if it makes the code clearer though.
Here's a complete example example:
Option(123).map { number =>
println(s"the number plus one is: ${number + 1}")
}Use parentheses and an underscore for anonymous functions that are:
- single binary operations
- a single method invocation on the input
- two or fewer unary methods on the input
Examples:
val list = List("list", "of", "strings")
list.filter(_.length > 2)
list.filter(_.contains("i"))If the function takes a single argument, then arguments and underscores should be omitted.
For example:
Option(123).map(println)is preferred over
Option(123).map(println(_))Prefer dot notation except for these specific scenarios:
- Specs2 matchers
- Akka
pipeTo,!,?
For example:
Option(someInt).map(println)is preferred over
Option(someInt) map printlnJava <=> Scala interoperation on primitives: Scala and Java booleans, for example, are not directly compatible, and require an implicit conversion between one another. Normally this is handled automagically by the Scala compiler, but the following code would reveal a compiler error:
Option(true).foreach(someMethodThatTakesAJavaBoolean)A named parameter is not necessary to achieve this. An underscore should be used to resolve the implicit conversion. To avoid confusion, please also add a note that a Scala <=> Java conversion is taking place:
Option(true).foreach(someMethodThatTakesAJavaBoolean(_)) // lol javaIn general, logic that handles a choice between two or more outcomes should prefer to use match.
When you match on any type, follow these rules:
- indent all
casestatements at the same level, and put the=>one space to the right of the closing) - if your expression is one line:
- put it on the same line as the
caseif doing so will not make the line excessively long - put it on the line below the
case, indented one level in from thecase - If your expression is more than one line, put it on the line below the case,
indented one level in from the
case. - Do not add extra newlines in between each case statement.
- Filters on case statements should be on the same level if doing so will not make the line excessively long.
Here's a complete example:
Option(123) match {
case Some(i: Int) if i > 0 =>
val intermediate = doWorkOn(i + 1)
doMoreWorkOn(intermediate)
case _ => 123
}Flows with Option values should be constructed using the match keyword as follows.
def stuff(i: Int): Int = { ... }
Option(123) match {
case None => 0
case Some(number) => stuff(number)
}The .fold operator should generally not be used. Simple, single-line patterns are acceptable for .fold, such as:
def stuff(i: Int): Int = { ... }
Option(123).fold(0)(stuff)Similarly, simple patterns are acceptable for .map with .getOrElse, such as:
def stuff(i: Int): Int = { ... }
Option(123).map(stuff).getOrElse(0)You should enforce expected type signatures, as match does not guarantee consistent types between match outcomes
(e.g. the None case could return Int, while the Some case could return String).
When creating Options, use
.opt.
If the value is a constant, use
.some
instead.
val doThisForConstants = "hello".some
val notThisForConstants = "goodbye".opt
val doThisForEverythingElse = foo().opt
val notThisForEverythingElse = bar().someFor comprehensions should generally not be wrapped in parentheses in order to recover, flatMap, etc. Instead, separate the for comprehension into its own variable and perform additional operations on that.
val userAddress = for {
address <- loadAddress()
} yield address
userAddress.recover {
// recover from loadAddress exception
}.flatMap {
// pull info from address, etc.
}In addition, if performing additional operations on the result of the yield as part of the result of the for comprehension itself, code should be separated by braces and begin on a newline. For example:
for {
address <- loadAddress() // returns Option
} yield {
address match {
case Some(s) => ...
case None => ...
}
}As a general practice, the ordering of case statements should be prioritized from most likely to be the executed to least likely.
For example, if you expect a Try to generally succeed, the first case in the match should be Success(s), followed by Failure(f).
The same goes for if/else statements, naturally.
Prefer ! and ? over .tell and .ask.
someActor1 ! msg
someActor2 ? msgis preferred over
someActor1.tell(msg)
someActor2.ask(msg)Write your tests using Specs2. Each
specification is a single class that extends Specification. Put each
specification into its own file. Inside each specification, follow these rules:
- create a single
traitinside yourSpecificationclass that extendsCommonImmutableSpecificationContext(from Cascade.) Most people name this traitContext. - Group tests into
classes,case classes orobjects at your discretion. - All of your grouped test
classes,case classes andobjectss should go inside your specification class and should extend yourContexttrait - All methods inside your test classes should be wrapped with
apply. When you do so,CommonImmutableSpecificationContextwill executebeforeandafterhooks automatically. - Your tests execute concurrently by default. Only change them to execute sequentially for a good reason, and document that reason in comments.
Here's an example of the above rules in code:
class MyTest extends Specification { override def is = s2"""
add(1, 2) should equal 3 ${Add().equals3()}
"""
trait Context extends CommonImmutableSpecificationContext
case class Add() extends Context {
def equals3 = apply {
add(1, 2) must beEqualTo(3)
}
}
}All classes, objects, traits, and methods should be documented. Generally, follow the documentation guidelines provided by the Scala Documentation Style Guide on ScalaDoc.
Rules:
- Classes that are instantiated via methods in a companion object must include ScalaDoc documentation with a code example.
- Abstract classes should be documented with an example of their intended implementation.
- Implicit wrapper classes must include ScalaDoc documentation with a code example.
- Public, protected, and package-private methods must include ScalaDoc documentation.
- Private methods should be documented, however it is left to the discretion of the developer as to the level of documentation.
- All methods must include
@throwsannotations if they throw an exception in their normal operation.
Use your best judgment otherwise, and err toward more documentation rather than less.
Several of these recommendations are adapted from the Scala Documentation Style Guide, including Declarations and Indentation. The guidelines presented in this document should supersede all other style recommendations.