Scala Best Practices
Examples
Keep it simple
Do not overcomplicate simple tasks. Most of the time you will need only:
• algebraic datatypes
• structural recursion
• monad-like api (map, flatMap, fold)
There is plenty of complicated stuff in Scala, such as:
• Cake pattern or Reader Monad for Dependency Injection.
• Passing arbitrary values as implicit arguments.
These things are not clear for newcomers: avoid using them before you understand them. Using advanced concepts without a real need obfuscates the code, making it less maintainable.
Don't pack too much in one expression.
• Find meaningful names for computation units.
• Use for comprehensions or map to combine computations together.
Let's say you have something like this:
if (userAuthorized.nonEmtpy) {
makeRequest().map {
case Success(respone) =>
someProcessing(..)
if (resendToUser) {
sendToUser(...)
}
...
}
}
If all your functions return Either or another Validation-like type, you can write:
for {
user <- authorizeUser
response <- requestToThirdParty(user)
_ <- someProcessing(...)
} {
sendToUser
}