SlideShare a Scribd company logo
Scala
Refactoring
Tomer Gabel, Scala Matsuri 2016
for Fun and Profit
楽しく役立つ Scala リファクタリング
Agenda
• For the next 40
minutes, we’ll:
– Look at examples
– Discuss patterns
– … and anti-patterns
– Showcase refactoring
techniques
例を通してパターンとアンチパターンを議論し、
リファクタリングのテクニックを説明する
Our Victim
• … is ScalaChess
– Provides a full domain
model for chess
– Good test coverage
– High quality code
– MIT license
– Integrated in lichess.org* ScalaChess is an open-source project by Thibault Duplessis
チェスのドメインモデルを備えるScalaChessを例にする
高品質でlichess.orgと統合されたMITライセンスのOSS
THE LAY OF THE
LAND前線の状況
Stringly Typed
“Used to describe an implementation
that needlessly relies on strings when
programmer & refactor friendly options
are available.”
-- Coding
Horror
アンチパターン:Stringly Typed
型付けできる所で不必要に文字列に頼った実装のこと
Stringly Typed
• Examples:
– Carrying unparsed data around
– Using empty strings instead of Options
case class Person(name: String, location: String)
def nearest(to: Person, all: List[Person]): Person = {
val geo: Point = Point.parse(to.location)
all.minBy(p => geo.distanceTo(Point.parse(p.location)))
}
1. Inefficient (space/time)
2. Error handling all over the place
3. What’s with all the boilerplate?
Stringly Typed の例1:
パースしてないデータを持ち回す
Stringly Typed
• Examples:
– Carrying unparsed data around
– Using empty strings instead of Options
case class Person(name: String, location: Point)
def nearest(to: Person, all: List[Person]): Person =
all.minBy(p => to.location distanceTo p.location)
1. Efficient (only parsed once)
2. Sane error handling
3. Zero boilerplate!
パース後のデータを使うことで効率的で、
エラー処理が容易に、お決まりの処理も不要になる
Stringly Typed
• Examples:
– Carrying unparsed data around
– Using empty strings instead of Options
case class Person(firstName: String, lastName: String)
def render(p: Person): String =
s"""
|<div id='first-name'>${p.firstName}</div>
|<div id='last-name'>${p.lastName}</div>
""".stripMargin
1. Nothing enforces emptiness check!
2. Scala has a great type for these :-)
Stringly Typed の例2:
Option の代わりに空文字を使う
REAL-WORLD EXAMPLE TIME!
Collective Abuse
• Scala has a massive
collection library
• Loads of built-ins too
– Case classes
– Functions and partials
– Tuples, tuples, tuples
• Fairly easy to abuse
Scalaにはたくさんのコレクション、caseクラス、関数、
タプルがある。これらは、実は簡単に濫用できてしまう
Collective Abuse
• Common anti-patterns:
– Too many inline steps
– Tuple overload
val actors: List[(Int, String, Double)] = // ...
def bestActor(query: String) =
actors.filter(_._2 contains query)
.sortBy(-_._3)
.map(_._1)
.headOption
1. What does this even do?!
2. How does data flow here?
アンチパターン:
一行に処理を詰め込み過ぎる
Collective Abuse
• Common anti-patterns:
– Too many inline steps
– Tuple overload
val actors: List[(Int, String, Double)] = // ...
def bestActor(query: String) = {
val matching = actors.filter(_._2 contains query)
val bestByScore = matching.sortBy(-_._3).headOption
bestByScore.map(_._1)
} Name intermediate steps!
中間状態に名前を付けよう!
Collective Abuse
• Common anti-patterns:
– Too many inline steps
– Tuple overload
val actors: List[(Int, String, Double)] = // ...
def bestActor(query: String) =
actors.filter(_._2 contains query)
.sortBy(-_._3)
.map(_._1)
.headOption
What’s with all these
underscores?
アンチパターン:
タプルの使いすぎ
Collective Abuse
• Common anti-patterns:
– Too many inline steps
– Tuple overload
case class Actor(id: Int, name: String, score: Double)
def bestActor(query: String, actors: List[Actor]) =
actors.filter(_.name contains query)
.sortBy(-_.score)
.map(_.id)
.headOption
Scala classes are cheap.
Use them.
Scala ではcaseクラスを簡単に定義できる
どんどん使おう
REAL-WORLD EXAMPLE TIME!
Questions?
tomer@tomergabel.com
@tomerg
http://il.linkedin.com/in/tomergabel
WE’RE DONE
HERE!

More Related Content

PPTX
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
PDF
How Scala code is expressed in the JVM
PDF
The Evolution of Scala / Scala進化論
PDF
Solid And Sustainable Development in Scala
PPTX
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
PDF
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
PPTX
From Ruby to Scala
PDF
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
How Scala code is expressed in the JVM
The Evolution of Scala / Scala進化論
Solid And Sustainable Development in Scala
Building a Unified Data Pipline in Spark / Apache Sparkを用いたBig Dataパイプラインの統一
Introduction to Spark SQL and Catalyst / Spark SQLおよびCalalystの紹介
From Ruby to Scala
Weaving Dataflows with Silk - ScalaMatsuri 2014, Tokyo

What's hot (20)

PDF
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
KEY
Static or Dynamic Typing? Why not both?
PDF
camel-scala.pdf
PDF
Zen of Akka
KEY
The Why and How of Scala at Twitter
PDF
Scala : language of the future
PPTX
Java Serialization Facts and Fallacies
PPTX
A Brief Intro to Scala
ODP
Refactoring to Scala DSLs and LiftOff 2009 Recap
PDF
Scarab: SAT-based Constraint Programming System in Scala / Scala上で実現された制約プログラ...
PDF
Why GC is eating all my CPU?
PPTX
Scala Refactoring for Fun and Profit
PDF
A Brief, but Dense, Intro to Scala
PPTX
Speaking Scala: Refactoring for Fun and Profit (Workshop)
PPTX
Millions quotes per second in pure java
PDF
[Start] Scala
PDF
A Sceptical Guide to Functional Programming
KEY
Scala Introduction
PDF
Akka and the Zen of Reactive System Design
PDF
Ruby Performance - The Last Mile - RubyConf India 2016
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
Static or Dynamic Typing? Why not both?
camel-scala.pdf
Zen of Akka
The Why and How of Scala at Twitter
Scala : language of the future
Java Serialization Facts and Fallacies
A Brief Intro to Scala
Refactoring to Scala DSLs and LiftOff 2009 Recap
Scarab: SAT-based Constraint Programming System in Scala / Scala上で実現された制約プログラ...
Why GC is eating all my CPU?
Scala Refactoring for Fun and Profit
A Brief, but Dense, Intro to Scala
Speaking Scala: Refactoring for Fun and Profit (Workshop)
Millions quotes per second in pure java
[Start] Scala
A Sceptical Guide to Functional Programming
Scala Introduction
Akka and the Zen of Reactive System Design
Ruby Performance - The Last Mile - RubyConf India 2016
Ad

Similar to Scala Refactoring for Fun and Profit (Japanese subtitles) (20)

PPT
Scala Days San Francisco
PDF
Scala for Java Programmers
PDF
Martin Odersky - Evolution of Scala
PDF
Scala overview
PDF
Scala In The Wild
PDF
Martin Odersky: What's next for Scala
PPTX
Scala final ppt vinay
PPTX
Taxonomy of Scala
PPTX
Scala in the Wild
PDF
Lecture1
PDF
Live coding scala 'the java of the future'
PPTX
Scala, Play 2.0 & Cloud Foundry
PPT
PDF
Rafael Bagmanov «Scala in a wild enterprise»
PDF
Scala, Akka, and Play: An Introduction on Heroku
PPTX
Spark - The Ultimate Scala Collections by Martin Odersky
PPTX
Scalaマクロ入門 bizr20170217
PDF
Scala Bot for Small Business
PPTX
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
PPTX
Exploring Java Heap Dumps (Oracle Code One 2018)
Scala Days San Francisco
Scala for Java Programmers
Martin Odersky - Evolution of Scala
Scala overview
Scala In The Wild
Martin Odersky: What's next for Scala
Scala final ppt vinay
Taxonomy of Scala
Scala in the Wild
Lecture1
Live coding scala 'the java of the future'
Scala, Play 2.0 & Cloud Foundry
Rafael Bagmanov «Scala in a wild enterprise»
Scala, Akka, and Play: An Introduction on Heroku
Spark - The Ultimate Scala Collections by Martin Odersky
Scalaマクロ入門 bizr20170217
Scala Bot for Small Business
A full Machine learning pipeline in Scikit-learn vs in scala-Spark: pros and ...
Exploring Java Heap Dumps (Oracle Code One 2018)
Ad

More from Tomer Gabel (20)

PDF
How shit works: Time
PDF
Nondeterministic Software for the Rest of Us
PDF
Slaying Sacred Cows: Deconstructing Dependency Injection
PDF
An Abridged Guide to Event Sourcing
PDF
How shit works: the CPU
PDF
How Shit Works: Storage
PDF
Java 8 and Beyond, a Scala Story
PDF
The Wix Microservice Stack
PDF
Onboarding at Scale
PPTX
Put Your Thinking CAP On
PPTX
Leveraging Scala Macros for Better Validation
PDF
A Field Guide to DSL Design in Scala
PPTX
Functional Leap of Faith (Keynote at JDay Lviv 2014)
PPTX
Scala Back to Basics: Type Classes
PDF
5 Bullets to Scala Adoption
PPTX
Nashorn: JavaScript that doesn’t suck (ILJUG)
PDF
Ponies and Unicorns With Scala
PPTX
Lab: JVM Production Debugging 101
PPTX
DevCon³: Scala Best Practices
PPTX
Maven for Dummies
How shit works: Time
Nondeterministic Software for the Rest of Us
Slaying Sacred Cows: Deconstructing Dependency Injection
An Abridged Guide to Event Sourcing
How shit works: the CPU
How Shit Works: Storage
Java 8 and Beyond, a Scala Story
The Wix Microservice Stack
Onboarding at Scale
Put Your Thinking CAP On
Leveraging Scala Macros for Better Validation
A Field Guide to DSL Design in Scala
Functional Leap of Faith (Keynote at JDay Lviv 2014)
Scala Back to Basics: Type Classes
5 Bullets to Scala Adoption
Nashorn: JavaScript that doesn’t suck (ILJUG)
Ponies and Unicorns With Scala
Lab: JVM Production Debugging 101
DevCon³: Scala Best Practices
Maven for Dummies

Recently uploaded (20)

PPT
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
PDF
737-MAX_SRG.pdf student reference guides
PDF
86236642-Electric-Loco-Shed.pdf jfkduklg
PDF
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
PPTX
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
PPTX
Fundamentals of safety and accident prevention -final (1).pptx
PDF
Exploratory_Data_Analysis_Fundamentals.pdf
PPTX
Fundamentals of Mechanical Engineering.pptx
PPT
Occupational Health and Safety Management System
PDF
PPT on Performance Review to get promotions
PDF
R24 SURVEYING LAB MANUAL for civil enggi
PPTX
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
PPTX
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PDF
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
PDF
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
PDF
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
PPTX
Safety Seminar civil to be ensured for safe working.
PDF
Categorization of Factors Affecting Classification Algorithms Selection
PDF
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
PDF
Mitigating Risks through Effective Management for Enhancing Organizational Pe...
Introduction, IoT Design Methodology, Case Study on IoT System for Weather Mo...
737-MAX_SRG.pdf student reference guides
86236642-Electric-Loco-Shed.pdf jfkduklg
keyrequirementskkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk
6ME3A-Unit-II-Sensors and Actuators_Handouts.pptx
Fundamentals of safety and accident prevention -final (1).pptx
Exploratory_Data_Analysis_Fundamentals.pdf
Fundamentals of Mechanical Engineering.pptx
Occupational Health and Safety Management System
PPT on Performance Review to get promotions
R24 SURVEYING LAB MANUAL for civil enggi
CURRICULAM DESIGN engineering FOR CSE 2025.pptx
MET 305 2019 SCHEME MODULE 2 COMPLETE.pptx
PREDICTION OF DIABETES FROM ELECTRONIC HEALTH RECORDS
The CXO Playbook 2025 – Future-Ready Strategies for C-Suite Leaders Cerebrai...
BIO-INSPIRED HORMONAL MODULATION AND ADAPTIVE ORCHESTRATION IN S-AI-GPT
Safety Seminar civil to be ensured for safe working.
Categorization of Factors Affecting Classification Algorithms Selection
Enhancing Cyber Defense Against Zero-Day Attacks using Ensemble Neural Networks
Mitigating Risks through Effective Management for Enhancing Organizational Pe...

Scala Refactoring for Fun and Profit (Japanese subtitles)

  • 1. Scala Refactoring Tomer Gabel, Scala Matsuri 2016 for Fun and Profit 楽しく役立つ Scala リファクタリング
  • 2. Agenda • For the next 40 minutes, we’ll: – Look at examples – Discuss patterns – … and anti-patterns – Showcase refactoring techniques 例を通してパターンとアンチパターンを議論し、 リファクタリングのテクニックを説明する
  • 3. Our Victim • … is ScalaChess – Provides a full domain model for chess – Good test coverage – High quality code – MIT license – Integrated in lichess.org* ScalaChess is an open-source project by Thibault Duplessis チェスのドメインモデルを備えるScalaChessを例にする 高品質でlichess.orgと統合されたMITライセンスのOSS
  • 4. THE LAY OF THE LAND前線の状況
  • 5. Stringly Typed “Used to describe an implementation that needlessly relies on strings when programmer & refactor friendly options are available.” -- Coding Horror アンチパターン:Stringly Typed 型付けできる所で不必要に文字列に頼った実装のこと
  • 6. Stringly Typed • Examples: – Carrying unparsed data around – Using empty strings instead of Options case class Person(name: String, location: String) def nearest(to: Person, all: List[Person]): Person = { val geo: Point = Point.parse(to.location) all.minBy(p => geo.distanceTo(Point.parse(p.location))) } 1. Inefficient (space/time) 2. Error handling all over the place 3. What’s with all the boilerplate? Stringly Typed の例1: パースしてないデータを持ち回す
  • 7. Stringly Typed • Examples: – Carrying unparsed data around – Using empty strings instead of Options case class Person(name: String, location: Point) def nearest(to: Person, all: List[Person]): Person = all.minBy(p => to.location distanceTo p.location) 1. Efficient (only parsed once) 2. Sane error handling 3. Zero boilerplate! パース後のデータを使うことで効率的で、 エラー処理が容易に、お決まりの処理も不要になる
  • 8. Stringly Typed • Examples: – Carrying unparsed data around – Using empty strings instead of Options case class Person(firstName: String, lastName: String) def render(p: Person): String = s""" |<div id='first-name'>${p.firstName}</div> |<div id='last-name'>${p.lastName}</div> """.stripMargin 1. Nothing enforces emptiness check! 2. Scala has a great type for these :-) Stringly Typed の例2: Option の代わりに空文字を使う
  • 10. Collective Abuse • Scala has a massive collection library • Loads of built-ins too – Case classes – Functions and partials – Tuples, tuples, tuples • Fairly easy to abuse Scalaにはたくさんのコレクション、caseクラス、関数、 タプルがある。これらは、実は簡単に濫用できてしまう
  • 11. Collective Abuse • Common anti-patterns: – Too many inline steps – Tuple overload val actors: List[(Int, String, Double)] = // ... def bestActor(query: String) = actors.filter(_._2 contains query) .sortBy(-_._3) .map(_._1) .headOption 1. What does this even do?! 2. How does data flow here? アンチパターン: 一行に処理を詰め込み過ぎる
  • 12. Collective Abuse • Common anti-patterns: – Too many inline steps – Tuple overload val actors: List[(Int, String, Double)] = // ... def bestActor(query: String) = { val matching = actors.filter(_._2 contains query) val bestByScore = matching.sortBy(-_._3).headOption bestByScore.map(_._1) } Name intermediate steps! 中間状態に名前を付けよう!
  • 13. Collective Abuse • Common anti-patterns: – Too many inline steps – Tuple overload val actors: List[(Int, String, Double)] = // ... def bestActor(query: String) = actors.filter(_._2 contains query) .sortBy(-_._3) .map(_._1) .headOption What’s with all these underscores? アンチパターン: タプルの使いすぎ
  • 14. Collective Abuse • Common anti-patterns: – Too many inline steps – Tuple overload case class Actor(id: Int, name: String, score: Double) def bestActor(query: String, actors: List[Actor]) = actors.filter(_.name contains query) .sortBy(-_.score) .map(_.id) .headOption Scala classes are cheap. Use them. Scala ではcaseクラスを簡単に定義できる どんどん使おう

Editor's Notes

  • #10: Source: http://stackoverflow.com/questions/5564074/scala-http-operations
  • #11: Source: http://scalaz.github.io/scalaz/scalaz-2.9.1-6.0.4/doc.sxr/scalaz/example/ExampleApplicative.scala.html
  • #12: Photo source: https://flic.kr/p/3xcrQG
  • #13: Image source: http://www.flickeringmyth.com/2015/06/fallout-4-graphics-and-why-visual-demands-are-dumb.html
  • #18: Image source: https://thisistwitchy.files.wordpress.com/2013/04/oh-the-horror.jpg
  • #19: Image source: http://onlinesalesstepbystep.com/wp-content/uploads/2014/08/Toppling-books.jpg
  • #24: Photo source: https://flic.kr/p/3xcrQG