SlideShare a Scribd company logo
Learning from
“Effective Scala”
              #akskscala 38
Scala study group at Akasaka, Tokyo, Japan
         Kazuhiro Sera @seratch
Effective Scala?

• http://twitter.github.com/effectivescala/
• Best practices from Twitter engineers
• Creative Commons BY 3.0 License
• Japanese version is also available (great
  work by @okapies and @scova0731)
Introduction
• A short essay that provides a set of best
  practices
• Libraries from Twitter - Finagle, Ostrich,
  Util, Gizzard, Scalding and more...
• Program in Scala, you’re not writing Java,
  nor Haskell, nor Python
• Assumes the reader is familiar with Scala
Formatting 1

• Consistent application of the same
  formatting rules will enhance readability
• Particular importance to Scala because its
  grammar has a high degree of overwrap
• Scala Style Guide and some additional rules
Formatting 2
• Indent: 2spaces, Straight-line length: 100
• External APIs should have longer and
  explanatory names
• Use val (= don’t rebind names)
• Avoid using ` to overload reserved names
• Active names for ops with side effects
Formatting 3
• Getters without `get` prefix
• Don’t repeat names that are already
  encapsulated - e.g. User.getUser(123)
• Wildcard import for more than 6 names
• Don’t use relative imports
• Put imports at the top (in one place)
Formatting 4
• Avoid using braces for simple expressions
• Use PartialFunction if possible
• Comments to explain the behavior of your
  code are bad sign
• Prefer “Obviously it works” to “it works,
  obviously” and restructure so
Types and Generics 1
• Fascinating but avoid type level
  programming in production code
• Use explicit return type annotations for
  public methods
• Immutable collections should be covariant
• Mutable collections should be invariant
Types and Generics 2
• Use type alias for convenient naming or
  clarify purpose
• Don’t subclassing when an alias will do
• Using implicits sparingly
• Ask yourself if there is a way to achieve the
  same thing without implicits
• “Pimp my library” pattern - e.g. RichInt
Collections 1
• Should read “collections design document”
• Prefer using immutable collections
• Use “mutable” namespace explicitly
• Receive the most generic collection type
  appropriate in methods/constructors
  (Iterable, Seq, Set, Map ...)
Collections 2
• Pipelining transformations leads to very
  succinct solutions but can also be confusing
  to the reader
• “val votesByLang = votes groupBy { case
  (lang, _) => lang }” instead of just
  “groupBy(_._1) “
• If you worry about namespace pollution,
  group expressions with {}
Collections 3
• Read “Performance Characterisitics”
• Use profiler (e.g.YourKit Java Profiler)
• Use arrays instead of lists for large
  sequences
• Use buffers when performance matters
• Not JavaConversions but JavaConverters
Concurrency
• Use Futures to manage concurrency
• Futures are declarative, composable and
  have principled handling of failures
• Prefer Future combinators
  (com.twitter.util.Future.join/collect)
• Reach for a concurrent collection after
  trying with a synchronized collection
Control structures 1
• Declarative style, more expression-oriented
• Recursion makes your programs simple
• Starts with a well-defined clean slate, no
  reference cells and invariants abound
• Check the tail call optimization application
  by the @tailrec annotation
Control structures 2

• Use returns to cut down branching and
  establish invariants
• Avoid using returns as you would do in
  imperative languages
• Avoid using returns inside of a closure
  because of hidden costs
Control structures 3
• for-comprehensions provides succinct and
  natural expressions
• Demerit: hidden costs to allocate and
  dispatch closures and unexpected
  semantics
• require/assert are useful when the type
  system cannot express the required
  invariants
Functional programming 1

• Value oriented programming (emphasizes
  the transformation of values over stateful
  mutation)
• Referentially transparent, stronger invaliants
• case classes as ADT(Algebraic Data Type)s
Functional programming 2

• Option type is a container which provides a
  safe alternative to the use of null
• Use “opt foreach { v => }” or pattern
  matching or getOrElse instead of
  “if(opt.isDefined) opt.get”
• Use Option(v) instead of Some(v)
Functional programming 3

• Might be more composability with a
  PartialFunction than returning an Option
• Destructuring bindings are particularly
  useful for tuples and case classes
• Lazy fields compute and memorizes a result
• Should make the cost model explicit and
  precisely control side-effects
Functional programming 4

• Use call-by-name only to construct natural
  DSLs (control constructs)
• Use call-by-name only in the last position of
  the last argument list
• Use explicit functions for multiple times
  execution or side-effecting
Object oriented programming 1


• Dependency Injection by typically defining
  trait and subclassing
• Injecting factories by using simple functions
• Keep traits short and orthogonal - e.g.
  Reader/Writer instead of IOer
Object oriented programming 2


• private[this] can aid performance
  optimizations
• Constrain visibility of singleton class types -
  e.g. def foo(): Foo = new Foo with Bar {}
• Don’t use structural types in normal use
Garbage collection

• Functional Scala code tends to generate
  more short-lived garbage than Java
• Don’t act without data, use profiling tools -
  e.g. heapster, gcprof
Java compatibility

• Sometimes your Scala code is not directly
  usable from Java (traits that contain
  implementation, collections, functions...)
• Sometimes need to separate Java APIs
• Write unit tests in Java
Twitter’s standard libraries 1


• Util: an extension to the Scala and Java
  standard libraries
• Finagle: RPC system - the kernel distributed
  systems components
Twitter’s standard libraries 2

• Future - a simple container(a type of
  collection) which hold the promise for the
  result of a computation which is not yet
  complete
• 3 states: pending, failed or completed
• Future#flatMap is useful to define
  composite operations
Twitter’s standard libraries 3

• Use callbacks(onSuccess) instead of foreach
• Future.value(), exception() creates pre-
  satisfied Futures
• Future.collect(), join() provide combinators
  that turn futures into one
• Future#cancel from consumers is
  propagated to its producer

More Related Content

PDF
DIG1108C Lesson 5 Fall 2014
PPTX
Java 8 Features
PPTX
Adobe Flash Actionscript language basics chapter-2
PDF
Puppet - The IT automation software
PPTX
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
PPTX
Lambda Expressions in Java 8
PPTX
Parallel Computing in .NET
PPT
09 string processing_with_regex copy
DIG1108C Lesson 5 Fall 2014
Java 8 Features
Adobe Flash Actionscript language basics chapter-2
Puppet - The IT automation software
Introduction of Java 8 with emphasis on Lambda Expressions and Streams
Lambda Expressions in Java 8
Parallel Computing in .NET
09 string processing_with_regex copy

What's hot (20)

PPTX
Functional programming for the Advanced Beginner
PPTX
Java Tutorial Lab 1
PDF
Extracts from "Clean code"
PPTX
Collections
PPTX
Analysis of a basic java program
PPTX
Java annotations
PPTX
Semantic DEX Components
PPTX
Introduction to Scala
PPTX
CSharp for Unity Day 3
PDF
Java 8 Lambda Expressions & Streams
PPTX
Java- Updates in java8-Mazenet solution
PPTX
Java related basic tutorial
PPTX
Java Tutorial Lab 6
PDF
Python libraries
PPTX
Java SE 8 - New Features
PPT
Lambdas
PPTX
What's new in Java 8
PPTX
Java 8 - Features Overview
PPTX
PowerCLI in the Enterprise Breaking the Magicians Code original
PPTX
java 8 new features
Functional programming for the Advanced Beginner
Java Tutorial Lab 1
Extracts from "Clean code"
Collections
Analysis of a basic java program
Java annotations
Semantic DEX Components
Introduction to Scala
CSharp for Unity Day 3
Java 8 Lambda Expressions & Streams
Java- Updates in java8-Mazenet solution
Java related basic tutorial
Java Tutorial Lab 6
Python libraries
Java SE 8 - New Features
Lambdas
What's new in Java 8
Java 8 - Features Overview
PowerCLI in the Enterprise Breaking the Magicians Code original
java 8 new features
Ad

Viewers also liked (14)

PDF
ScalikeJDBC Tutorial for Beginners
PPTX
Scala-Ls1
PPTX
Java/Scala Lab 2016. Александр Конопко: Машинное обучение в Spark.
PDF
Distributed machine learning 101 using apache spark from the browser
PDF
Scala for Machine Learning
PPTX
Scalable and Flexible Machine Learning With Scala @ LinkedIn
PPTX
Using Deep Learning for Recommendation
PDF
Effective Scala (SoftShake 2013)
PDF
Getting Started with Deep Learning using Scala
PDF
PredictionIO – A Machine Learning Server in Scala – SF Scala
PPTX
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
PPTX
Machine Learning with Scala
PDF
Large-Scale Machine Learning with Apache Spark
PPTX
Real time Analytics with Apache Kafka and Apache Spark
ScalikeJDBC Tutorial for Beginners
Scala-Ls1
Java/Scala Lab 2016. Александр Конопко: Машинное обучение в Spark.
Distributed machine learning 101 using apache spark from the browser
Scala for Machine Learning
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Using Deep Learning for Recommendation
Effective Scala (SoftShake 2013)
Getting Started with Deep Learning using Scala
PredictionIO – A Machine Learning Server in Scala – SF Scala
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
Machine Learning with Scala
Large-Scale Machine Learning with Apache Spark
Real time Analytics with Apache Kafka and Apache Spark
Ad

Similar to Learning from "Effective Scala" (20)

PDF
Working With Concurrency In Java 8
PPTX
PPTX
Java and the JVM
PPTX
Design p atterns
PPTX
TDD and the Legacy Code Black Hole
PPTX
Javasession6
PPTX
Reading Notes : the practice of programming
PPTX
Javascript best practices
PPTX
Code reviews
PPTX
Apex code (Salesforce)
PPTX
Scala, Play 2.0 & Cloud Foundry
PDF
Scala Bay Meetup - The state of Scala code style and quality
PDF
Game Programming 04 - Style & Design Principles
PDF
Variables in Pharo
PPTX
Quick Interview Preparation for C# All Concepts
PPTX
Code reviews
PPTX
Improved Developer Productivity In JDK8
PPTX
PPT
Chapter 4_Introduction to Patterns.ppt
Working With Concurrency In Java 8
Java and the JVM
Design p atterns
TDD and the Legacy Code Black Hole
Javasession6
Reading Notes : the practice of programming
Javascript best practices
Code reviews
Apex code (Salesforce)
Scala, Play 2.0 & Cloud Foundry
Scala Bay Meetup - The state of Scala code style and quality
Game Programming 04 - Style & Design Principles
Variables in Pharo
Quick Interview Preparation for C# All Concepts
Code reviews
Improved Developer Productivity In JDK8
Chapter 4_Introduction to Patterns.ppt

More from Kazuhiro Sera (20)

PDF
All I learned while working on a Scala OSS project for over six years #ScalaM...
PDF
Contributing to Scala OSS from East Asia #ScalaMatsuri
PDF
Skinny Meetup Tokyo 2 日本語スライド
PDF
Skinny 2 Update
PDF
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarcon
PDF
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageek
PDF
Future on Servlet #scala_ks
PDF
Servlet と Future の関わり方 #scala_ks
PDF
マイクロサービス運用の所感 #m3dev
PDF
Scala が支える医療系ウェブサービス #jissenscala
PDF
Scala on Rails #rakutentech
PDF
Solid And Sustainable Development in Scala
PDF
Beginning Scala with Skinny Framework #jjug_ccc
PDF
[Japanese] Skinny Framework で始める Scala #jjug_ccc #ccc_r24
PDF
Skinny Framework 1.0.0
PDF
Skinny Framework Progress Situation
PDF
Skinny Framework 進捗どうですか? #fud_scala
PDF
テストの運用について #m3dev
PDF
めんどくさくない Scala #kwkni_scala
PDF
歌舞伎座.tech 1 LT - ScalikeJDBC Async & Skinny Framework #kbkz_tech
All I learned while working on a Scala OSS project for over six years #ScalaM...
Contributing to Scala OSS from East Asia #ScalaMatsuri
Skinny Meetup Tokyo 2 日本語スライド
Skinny 2 Update
Seasar ユーザだったプログラマが目指す OSS の世界展開 #seasarcon
Java エンジニアチームが始めやすい Scala コーディングスタイル #ichigayageek
Future on Servlet #scala_ks
Servlet と Future の関わり方 #scala_ks
マイクロサービス運用の所感 #m3dev
Scala が支える医療系ウェブサービス #jissenscala
Scala on Rails #rakutentech
Solid And Sustainable Development in Scala
Beginning Scala with Skinny Framework #jjug_ccc
[Japanese] Skinny Framework で始める Scala #jjug_ccc #ccc_r24
Skinny Framework 1.0.0
Skinny Framework Progress Situation
Skinny Framework 進捗どうですか? #fud_scala
テストの運用について #m3dev
めんどくさくない Scala #kwkni_scala
歌舞伎座.tech 1 LT - ScalikeJDBC Async & Skinny Framework #kbkz_tech

Recently uploaded (20)

PPT
Teaching material agriculture food technology
PDF
KodekX | Application Modernization Development
PPTX
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Encapsulation_ Review paper, used for researhc scholars
PDF
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
PPTX
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPTX
Programs and apps: productivity, graphics, security and other tools
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PDF
Chapter 3 Spatial Domain Image Processing.pdf
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
PPTX
Big Data Technologies - Introduction.pptx
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Machine learning based COVID-19 study performance prediction
Teaching material agriculture food technology
KodekX | Application Modernization Development
ACSFv1EN-58255 AWS Academy Cloud Security Foundations.pptx
Diabetes mellitus diagnosis method based random forest with bat algorithm
Encapsulation_ Review paper, used for researhc scholars
Peak of Data & AI Encore- AI for Metadata and Smarter Workflows
Effective Security Operations Center (SOC) A Modern, Strategic, and Threat-In...
Digital-Transformation-Roadmap-for-Companies.pptx
Programs and apps: productivity, graphics, security and other tools
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
Dropbox Q2 2025 Financial Results & Investor Presentation
Chapter 3 Spatial Domain Image Processing.pdf
The AUB Centre for AI in Media Proposal.docx
Spectral efficient network and resource selection model in 5G networks
Review of recent advances in non-invasive hemoglobin estimation
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
Big Data Technologies - Introduction.pptx
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Machine learning based COVID-19 study performance prediction

Learning from "Effective Scala"

  • 1. Learning from “Effective Scala” #akskscala 38 Scala study group at Akasaka, Tokyo, Japan Kazuhiro Sera @seratch
  • 2. Effective Scala? • http://twitter.github.com/effectivescala/ • Best practices from Twitter engineers • Creative Commons BY 3.0 License • Japanese version is also available (great work by @okapies and @scova0731)
  • 3. Introduction • A short essay that provides a set of best practices • Libraries from Twitter - Finagle, Ostrich, Util, Gizzard, Scalding and more... • Program in Scala, you’re not writing Java, nor Haskell, nor Python • Assumes the reader is familiar with Scala
  • 4. Formatting 1 • Consistent application of the same formatting rules will enhance readability • Particular importance to Scala because its grammar has a high degree of overwrap • Scala Style Guide and some additional rules
  • 5. Formatting 2 • Indent: 2spaces, Straight-line length: 100 • External APIs should have longer and explanatory names • Use val (= don’t rebind names) • Avoid using ` to overload reserved names • Active names for ops with side effects
  • 6. Formatting 3 • Getters without `get` prefix • Don’t repeat names that are already encapsulated - e.g. User.getUser(123) • Wildcard import for more than 6 names • Don’t use relative imports • Put imports at the top (in one place)
  • 7. Formatting 4 • Avoid using braces for simple expressions • Use PartialFunction if possible • Comments to explain the behavior of your code are bad sign • Prefer “Obviously it works” to “it works, obviously” and restructure so
  • 8. Types and Generics 1 • Fascinating but avoid type level programming in production code • Use explicit return type annotations for public methods • Immutable collections should be covariant • Mutable collections should be invariant
  • 9. Types and Generics 2 • Use type alias for convenient naming or clarify purpose • Don’t subclassing when an alias will do • Using implicits sparingly • Ask yourself if there is a way to achieve the same thing without implicits • “Pimp my library” pattern - e.g. RichInt
  • 10. Collections 1 • Should read “collections design document” • Prefer using immutable collections • Use “mutable” namespace explicitly • Receive the most generic collection type appropriate in methods/constructors (Iterable, Seq, Set, Map ...)
  • 11. Collections 2 • Pipelining transformations leads to very succinct solutions but can also be confusing to the reader • “val votesByLang = votes groupBy { case (lang, _) => lang }” instead of just “groupBy(_._1) “ • If you worry about namespace pollution, group expressions with {}
  • 12. Collections 3 • Read “Performance Characterisitics” • Use profiler (e.g.YourKit Java Profiler) • Use arrays instead of lists for large sequences • Use buffers when performance matters • Not JavaConversions but JavaConverters
  • 13. Concurrency • Use Futures to manage concurrency • Futures are declarative, composable and have principled handling of failures • Prefer Future combinators (com.twitter.util.Future.join/collect) • Reach for a concurrent collection after trying with a synchronized collection
  • 14. Control structures 1 • Declarative style, more expression-oriented • Recursion makes your programs simple • Starts with a well-defined clean slate, no reference cells and invariants abound • Check the tail call optimization application by the @tailrec annotation
  • 15. Control structures 2 • Use returns to cut down branching and establish invariants • Avoid using returns as you would do in imperative languages • Avoid using returns inside of a closure because of hidden costs
  • 16. Control structures 3 • for-comprehensions provides succinct and natural expressions • Demerit: hidden costs to allocate and dispatch closures and unexpected semantics • require/assert are useful when the type system cannot express the required invariants
  • 17. Functional programming 1 • Value oriented programming (emphasizes the transformation of values over stateful mutation) • Referentially transparent, stronger invaliants • case classes as ADT(Algebraic Data Type)s
  • 18. Functional programming 2 • Option type is a container which provides a safe alternative to the use of null • Use “opt foreach { v => }” or pattern matching or getOrElse instead of “if(opt.isDefined) opt.get” • Use Option(v) instead of Some(v)
  • 19. Functional programming 3 • Might be more composability with a PartialFunction than returning an Option • Destructuring bindings are particularly useful for tuples and case classes • Lazy fields compute and memorizes a result • Should make the cost model explicit and precisely control side-effects
  • 20. Functional programming 4 • Use call-by-name only to construct natural DSLs (control constructs) • Use call-by-name only in the last position of the last argument list • Use explicit functions for multiple times execution or side-effecting
  • 21. Object oriented programming 1 • Dependency Injection by typically defining trait and subclassing • Injecting factories by using simple functions • Keep traits short and orthogonal - e.g. Reader/Writer instead of IOer
  • 22. Object oriented programming 2 • private[this] can aid performance optimizations • Constrain visibility of singleton class types - e.g. def foo(): Foo = new Foo with Bar {} • Don’t use structural types in normal use
  • 23. Garbage collection • Functional Scala code tends to generate more short-lived garbage than Java • Don’t act without data, use profiling tools - e.g. heapster, gcprof
  • 24. Java compatibility • Sometimes your Scala code is not directly usable from Java (traits that contain implementation, collections, functions...) • Sometimes need to separate Java APIs • Write unit tests in Java
  • 25. Twitter’s standard libraries 1 • Util: an extension to the Scala and Java standard libraries • Finagle: RPC system - the kernel distributed systems components
  • 26. Twitter’s standard libraries 2 • Future - a simple container(a type of collection) which hold the promise for the result of a computation which is not yet complete • 3 states: pending, failed or completed • Future#flatMap is useful to define composite operations
  • 27. Twitter’s standard libraries 3 • Use callbacks(onSuccess) instead of foreach • Future.value(), exception() creates pre- satisfied Futures • Future.collect(), join() provide combinators that turn futures into one • Future#cancel from consumers is propagated to its producer

Editor's Notes