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

What's hot (20)

PPTX
Functional programming for the Advanced Beginner
Luis Atencio
 
PPTX
Java Tutorial Lab 1
Berk Soysal
 
PDF
Extracts from "Clean code"
VlatkaPavii
 
PPTX
Collections
Marwa Dosoky
 
PPTX
Analysis of a basic java program
Sujit Kumar
 
PPTX
Java annotations
Sujit Kumar
 
PPTX
Semantic DEX Components
David Price
 
PPTX
Introduction to Scala
Viyaan Jhiingade
 
PPTX
CSharp for Unity Day 3
Duong Thanh
 
PDF
Java 8 Lambda Expressions & Streams
NewCircle Training
 
PPTX
Java- Updates in java8-Mazenet solution
Mazenetsolution
 
PPTX
Java related basic tutorial
Manzur Ashraf
 
PPTX
Java Tutorial Lab 6
Berk Soysal
 
PDF
Python libraries
Prof. Dr. K. Adisesha
 
PPTX
Java SE 8 - New Features
Naveen Hegde
 
PPT
Lambdas
malliksunkara
 
PPTX
What's new in Java 8
Kyle Smith
 
PPTX
Java 8 - Features Overview
Sergii Stets
 
PPTX
PowerCLI in the Enterprise Breaking the Magicians Code original
jonathanmedd
 
PPTX
java 8 new features
Rohit Verma
 
Functional programming for the Advanced Beginner
Luis Atencio
 
Java Tutorial Lab 1
Berk Soysal
 
Extracts from "Clean code"
VlatkaPavii
 
Collections
Marwa Dosoky
 
Analysis of a basic java program
Sujit Kumar
 
Java annotations
Sujit Kumar
 
Semantic DEX Components
David Price
 
Introduction to Scala
Viyaan Jhiingade
 
CSharp for Unity Day 3
Duong Thanh
 
Java 8 Lambda Expressions & Streams
NewCircle Training
 
Java- Updates in java8-Mazenet solution
Mazenetsolution
 
Java related basic tutorial
Manzur Ashraf
 
Java Tutorial Lab 6
Berk Soysal
 
Python libraries
Prof. Dr. K. Adisesha
 
Java SE 8 - New Features
Naveen Hegde
 
Lambdas
malliksunkara
 
What's new in Java 8
Kyle Smith
 
Java 8 - Features Overview
Sergii Stets
 
PowerCLI in the Enterprise Breaking the Magicians Code original
jonathanmedd
 
java 8 new features
Rohit Verma
 

Viewers also liked (14)

PDF
ScalikeJDBC Tutorial for Beginners
Kazuhiro Sera
 
PPTX
Scala-Ls1
Aniket Joshi
 
PPTX
Java/Scala Lab 2016. Александр Конопко: Машинное обучение в Spark.
GeeksLab Odessa
 
PDF
Distributed machine learning 101 using apache spark from the browser
Andy Petrella
 
PDF
Scala for Machine Learning
Patrick Nicolas
 
PPTX
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Vitaly Gordon
 
PPTX
Using Deep Learning for Recommendation
Eduardo Gonzalez
 
PDF
Effective Scala (SoftShake 2013)
mircodotta
 
PDF
Getting Started with Deep Learning using Scala
Taisuke Oe
 
PDF
PredictionIO – A Machine Learning Server in Scala – SF Scala
predictionio
 
PPTX
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
Jose Quesada (hiring)
 
PPTX
Machine Learning with Scala
Susan Eraly
 
PDF
Large-Scale Machine Learning with Apache Spark
DB Tsai
 
PPTX
Real time Analytics with Apache Kafka and Apache Spark
Rahul Jain
 
ScalikeJDBC Tutorial for Beginners
Kazuhiro Sera
 
Scala-Ls1
Aniket Joshi
 
Java/Scala Lab 2016. Александр Конопко: Машинное обучение в Spark.
GeeksLab Odessa
 
Distributed machine learning 101 using apache spark from the browser
Andy Petrella
 
Scala for Machine Learning
Patrick Nicolas
 
Scalable and Flexible Machine Learning With Scala @ LinkedIn
Vitaly Gordon
 
Using Deep Learning for Recommendation
Eduardo Gonzalez
 
Effective Scala (SoftShake 2013)
mircodotta
 
Getting Started with Deep Learning using Scala
Taisuke Oe
 
PredictionIO – A Machine Learning Server in Scala – SF Scala
predictionio
 
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
Jose Quesada (hiring)
 
Machine Learning with Scala
Susan Eraly
 
Large-Scale Machine Learning with Apache Spark
DB Tsai
 
Real time Analytics with Apache Kafka and Apache Spark
Rahul Jain
 
Ad

Similar to Learning from "Effective Scala" (20)

PDF
Scala Bay Meetup - The state of Scala code style and quality
Jaime Jorge
 
PDF
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
Scala - from "Hello, World" to "Heroku Scale"
Salesforce Developers
 
PPTX
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
PDF
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
PDF
Scala and jvm_languages_praveen_technologist
pmanvi
 
PDF
Scala a case4
lee.gilbert
 
PDF
Scala In The Wild
djspiewak
 
PPTX
Scala in practice
Tomer Gabel
 
PPTX
Scala - The Simple Parts, SFScala presentation
Martin Odersky
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
PPTX
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
PDF
Quick introduction to scala
Mohammad Hossein Rimaz
 
Scala Bay Meetup - The state of Scala code style and quality
Jaime Jorge
 
Scala, Akka, and Play: An Introduction on Heroku
Havoc Pennington
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
Miles Sabin
 
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
Hiroshi Ono
 
Scala - from "Hello, World" to "Heroku Scale"
Salesforce Developers
 
Scala, Play 2.0 & Cloud Foundry
Pray Desai
 
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
Scala and jvm_languages_praveen_technologist
pmanvi
 
Scala a case4
lee.gilbert
 
Scala In The Wild
djspiewak
 
Scala in practice
Tomer Gabel
 
Scala - The Simple Parts, SFScala presentation
Martin Odersky
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
ScalaDays 2013 Keynote Speech by Martin Odersky
Typesafe
 
Quick introduction to scala
Mohammad Hossein Rimaz
 
Ad

More from Kazuhiro Sera (20)

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

Recently uploaded (20)

PDF
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
PDF
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PDF
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
PPTX
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 
Bitcoin for Millennials podcast with Bram, Power Laws of Bitcoin
Stephen Perrenod
 
Newgen Beyond Frankenstein_Build vs Buy_Digital_version.pdf
darshakparmar
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
CIFDAQ Token Spotlight for 9th July 2025
CIFDAQ
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Empower Inclusion Through Accessible Java Applications
Ana-Maria Mihalceanu
 
WooCommerce Workshop: Bring Your Laptop
Laura Hartwig
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Transcript: New from BookNet Canada for 2025: BNC BiblioShare - Tech Forum 2025
BookNet Canada
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Using FME to Develop Self-Service CAD Applications for a Major UK Police Force
Safe Software
 

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