SlideShare a Scribd company logo
2019
Badr Baddou - Loïc Knuchel
@GraalSeeker @loicknuchel
@GraalSeeker
@loicknuchel
The ugly truth
Hello !
Badr Baddou
Scala dev @ Zeenea
@GraalSeeker
Loïc Knuchel
Tech lead @ Zeenea
@loicknuchel
Scala
FP
DDD
Property based testing
Your next data catalog
#Data
#Documentation
#Glossary
#Lineage
#Gouvernance
@GraalSeeker
@loicknuchel
Common bad practices
● Do not use null and throw
● Avoid isEmpty / get
● Ban symbols in function names
● Pay attention of primitive types use
● Do not let library conventions leak in your code
● DRY overuse
● Beware of mixing paradigms
@GraalSeeker
@loicknuchel
Primitive
obsession
● Primitive types: Int, String, Boolean…
● They do not carry semantics
○ Int, String vs FileSize, Bandwidth, RelPath, Email…
● They are indistinguishable
○ String <=> String vs UserId <!> CommentId
● You don’t known if they were validated
○ String/String vs Email/CheckedEmail
● You have no helper methods
○ path.split(“/”).dropRight(1).mkString(“/”) vs path.getParent()
@GraalSeeker
@loicknuchel
Library-
splaining
Write a wrapper to protect from library conventions
● Anti corruption layer (DDD)
● Do types conversions
○ null <=> Option
○ throw <=> Try, Either
○ Java collections <=> Scala collections
○ primitive types <=> dedicated types => Type Safety o/
○ Any <=> ADT
● Paradigm shifts
○ mutable <=> immutable
○ currying
○ sync <=> async (dedicated thread pool)
@GraalSeeker
@loicknuchel
Mixing
paradigms class User() {
def updatedAt(): Option[Instant] =
null
def validEmail(): Try[String] =
throw new IllegalArgumentException("Email is invalid")
}
@GraalSeeker
@loicknuchel
DRY
overuse
case class User(id: Option[String],
name: String,
email: Option[String] = None,
friends: Seq[String] = Seq(),
admin: Boolean = false)
case class UserCreation(name: String,
email: String)
case class User(id: String,
name: String,
email: String)
case class UserFull(id: String,
name: String,
email: String,
friends: Seq[String],
admin: Boolean)
@GraalSeeker
@loicknuchel
Real code is
(often) a mess
● very long
● inconsitencies
● over generalization (DRY)
@GraalSeeker
@loicknuchel
Conciseness
over
readability
val tuple: (Int, Int) =
Map("id" -> ("badr", 13))
.flatMap(e => List(e._2))
.map(_._2 + 1)
./:((0, 0))((a, b) => (a._1 - 1, a._2 + b))
● Conciseness ≠ Clarity
● No semantics
Symbols
Tuple
Bad naming
@GraalSeeker
@loicknuchel
Solution
val tuple: (Int, Int) =
Map("id" -> ("badr", 13))
.flatMap(e => List(e._2))
.map(_._2 + 1)
./:((0, 0))((a, b) => (a._1 - 1, a._2 + b))
case class User(name: String, age: Int)
val tuple2: (Int, Int) =
Map("id" -> User("badr", 13))
.flatMap { case (_, value) => List(value) }
.map(user => user.age + 1)
.foldLeft((0, 0))((acc, e) => (acc._1 - 1, acc._2 + e))
“The most common things you want to do should be the most concise,
while the less common things should be more verbose”
Lihayo
No symbols
Use class
not tuples
Named pattern matching
Named value
@GraalSeeker
@loicknuchel
Powerful
Feature
misuse
final case class Arc(name: String)
def main() {
Arc("zzz").show()
}
case class RichArc(value: Arc) {
def show() = s"${value.name} is a rich Arc"
}
implicit def richArc(arc: Arc): RichArc = RichArc(arc)
// Problem conversion can apply when not needed
def createRichArc(): RichArc = {
// conversion not needed here
Arc("aaa")
}
@GraalSeeker
@loicknuchel
Solution
object Syntax {
implicit case class EnrichArc(value: Arc) extends AnyVal {
def show() = s"${value.name} is a rich Arc"
}
}
def main() {
import Syntax._
Arc("zzz").show()
}
@GraalSeeker
@loicknuchel
Apply
misuse
def main(args: Array[String]): Unit = {
val arc = Arc("id", "name")
}
// returns RichArc !!!
object Arc {
def apply(id: String, name: String): RichArc = {
val (in, out) = nodeRepo.getNodes(id).get // throws :(
RichArc(id, name, in, out)
}
}
case class Node(id: String, name: String)
case class Arc(id: String, name: String)
case class RichArc(id: String,
name: String,
in: Option[Node],
out: Option[Node])
@GraalSeeker
@loicknuchel
Solution object Arc {
def apply(id: String, name: String): RichArc = {
val (in, out) = nodeRepo.getNodes(id).get // throws :(
RichArc(id, name, in, out)
}
}
case class NodeRepo() {
def getNodes(id: String): Try[(Option[Node], Option[Node])] = ???
}
object RichArc {
def from(id: String, name: String): Try[RichArc] = {
nodeRepo.getNodes(id).map { case (in, out) =>
RichArc(id, name, in, out)
}
}
}
@GraalSeeker
@loicknuchel
hide and seek
implicits
object App {
def main(args: Array[String]): Unit = {
val p: PropertyValue = 1
val q: PropertyValue = true
val r: PropertyValue = "toto"
}
}
package object propertyHelpers {
implicit def build(v: Any): PropertyValue =
PropertyValue(v)
}
// there should be some implicits here
// but no import
// where to look???
“Package objects can contain arbitrary definitions.
For instance, they are frequently used to hold
package-wide implicit conversions.”
https://docs.scala-lang.org/tour/package-objects.html
@GraalSeeker
@loicknuchel
Define operator
val name: Prop[String] = Prop("name", StrWrap)
val score: Prop[Int] = Prop("score", IntWrap)
val props = Props(
name -> "Jean",
score -> 10)
@GraalSeeker
@loicknuchel
How it
works?
val name: Prop[String] = Prop("name", StrWrap)
val score: Prop[Int] = Prop("score", IntWrap)
val props = Props(
name -> "Jean",
score -> 10)
case class Props(in: Map[Prop.Name, Prop.Value])
object Props {
def apply(in: (Prop.Name, Prop.Value)*): Props =
new Props(in.toMap)
}
// look for implicits
case class Prop[A](name:Name, wrap:Wrap[A]) {
def ->(value: A): (Prop.Name, Prop.Value) =
(name, wrap.encode(value))
}
@GraalSeeker
@loicknuchel
Resources
● https://github.com/loicknuchel/scala-bad-practices
● http://bit.ly/scala-bad-practices
● https://github.com/zeenea/scala-best-practices

More Related Content

What's hot

Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
hmanjarawala
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
JavaDayUA
 
GDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván ZaeraGDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván Zaera
Jc Miñarro
 
Green dao
Green daoGreen dao
Green dao
彥彬 洪
 
J query1
J query1J query1
J query1
Manav Prasad
 
J query
J queryJ query
J query
Manav Prasad
 
GreenDao Introduction
GreenDao IntroductionGreenDao Introduction
GreenDao Introduction
Booch Lin
 
C# 7
C# 7C# 7
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
Mohammad Shaker
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
Mohammad Shaker
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript Dhananjay Kumar
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
jessitron
 
Green dao
Green daoGreen dao
Green dao
Droidcon Berlin
 
PDBC
PDBCPDBC
PDBC
Sunil OS
 
Humane assessment: Taming the elephant from the development room
Humane assessment: Taming the elephant from the development roomHumane assessment: Taming the elephant from the development room
Humane assessment: Taming the elephant from the development room
Tudor Girba
 
OOP v3
OOP v3OOP v3
OOP v3
Sunil OS
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
Luis Azevedo
 
Collection v3
Collection v3Collection v3
Collection v3
Sunil OS
 
Jazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipseJazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with Eclipse
Peter Friese
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
Alexander Zaidel
 

What's hot (20)

Introduction to csharp
Introduction to csharpIntroduction to csharp
Introduction to csharp
 
Monads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy DyagilevMonads and Monoids by Oleksiy Dyagilev
Monads and Monoids by Oleksiy Dyagilev
 
GDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván ZaeraGDG Madrid - Dart Event - By Iván Zaera
GDG Madrid - Dart Event - By Iván Zaera
 
Green dao
Green daoGreen dao
Green dao
 
J query1
J query1J query1
J query1
 
J query
J queryJ query
J query
 
GreenDao Introduction
GreenDao IntroductionGreenDao Introduction
GreenDao Introduction
 
C# 7
C# 7C# 7
C# 7
 
C# Starter L02-Classes and Objects
C# Starter L02-Classes and ObjectsC# Starter L02-Classes and Objects
C# Starter L02-Classes and Objects
 
C# Starter L04-Collections
C# Starter L04-CollectionsC# Starter L04-Collections
C# Starter L04-Collections
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
Contracts in-clojure-pete
Contracts in-clojure-peteContracts in-clojure-pete
Contracts in-clojure-pete
 
Green dao
Green daoGreen dao
Green dao
 
PDBC
PDBCPDBC
PDBC
 
Humane assessment: Taming the elephant from the development room
Humane assessment: Taming the elephant from the development roomHumane assessment: Taming the elephant from the development room
Humane assessment: Taming the elephant from the development room
 
OOP v3
OOP v3OOP v3
OOP v3
 
iPhone Development Intro
iPhone Development IntroiPhone Development Intro
iPhone Development Intro
 
Collection v3
Collection v3Collection v3
Collection v3
 
Jazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with EclipseJazoon 2010 - Building DSLs with Eclipse
Jazoon 2010 - Building DSLs with Eclipse
 
Scala best practices
Scala best practicesScala best practices
Scala best practices
 

Similar to Scala bad practices, scala.io 2019

Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
Pascal-Louis Perez
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
adam1davis
 
TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...
Igalia
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
Julien Wetterwald
 
Geo data analytics
Geo data analyticsGeo data analytics
Geo data analytics
Daniel Marcous
 
Reactive Web Applications with Scala & Liftweb - CodeWeek 2015
Reactive Web Applications with Scala & Liftweb - CodeWeek 2015Reactive Web Applications with Scala & Liftweb - CodeWeek 2015
Reactive Web Applications with Scala & Liftweb - CodeWeek 2015
Andrea Zaza
 
Codeweek 2015 - Reactive Web Applications with Scala and LIFT framework
Codeweek 2015 - Reactive Web Applications with Scala and LIFT frameworkCodeweek 2015 - Reactive Web Applications with Scala and LIFT framework
Codeweek 2015 - Reactive Web Applications with Scala and LIFT framework
Riccardo Sirigu
 
COLLADA & WebGL
COLLADA & WebGLCOLLADA & WebGL
COLLADA & WebGL
Remi Arnaud
 
Understanding Connected Data through Visualization
Understanding Connected Data through VisualizationUnderstanding Connected Data through Visualization
Understanding Connected Data through Visualization
Sebastian Müller
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
Michael Pirnat
 
Introduction to spark
Introduction to sparkIntroduction to spark
Introduction to spark
Duyhai Doan
 
Fancy talk
Fancy talkFancy talk
When RegEx is not enough
When RegEx is not enoughWhen RegEx is not enough
When RegEx is not enough
Nati Cohen
 
Sorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifySorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at Spotify
Neville Li
 
More expressive types for spark with frameless
More expressive types for spark with framelessMore expressive types for spark with frameless
More expressive types for spark with frameless
Miguel Pérez Pasalodos
 
Inductive Triple Graphs: A purely functional approach to represent RDF
Inductive Triple Graphs: A purely functional approach to represent RDFInductive Triple Graphs: A purely functional approach to represent RDF
Inductive Triple Graphs: A purely functional approach to represent RDF
Jose Emilio Labra Gayo
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
Wayne Tsai
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
Andreas Dewes
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
Domenic Denicola
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
Fwdays
 

Similar to Scala bad practices, scala.io 2019 (20)

Applying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing SpeedApplying Compiler Techniques to Iterate At Blazing Speed
Applying Compiler Techniques to Iterate At Blazing Speed
 
Learning groovy -EU workshop
Learning groovy  -EU workshopLearning groovy  -EU workshop
Learning groovy -EU workshop
 
TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...TC39: How we work, what we are working on, and how you can get involved (dotJ...
TC39: How we work, what we are working on, and how you can get involved (dotJ...
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
Geo data analytics
Geo data analyticsGeo data analytics
Geo data analytics
 
Reactive Web Applications with Scala & Liftweb - CodeWeek 2015
Reactive Web Applications with Scala & Liftweb - CodeWeek 2015Reactive Web Applications with Scala & Liftweb - CodeWeek 2015
Reactive Web Applications with Scala & Liftweb - CodeWeek 2015
 
Codeweek 2015 - Reactive Web Applications with Scala and LIFT framework
Codeweek 2015 - Reactive Web Applications with Scala and LIFT frameworkCodeweek 2015 - Reactive Web Applications with Scala and LIFT framework
Codeweek 2015 - Reactive Web Applications with Scala and LIFT framework
 
COLLADA & WebGL
COLLADA & WebGLCOLLADA & WebGL
COLLADA & WebGL
 
Understanding Connected Data through Visualization
Understanding Connected Data through VisualizationUnderstanding Connected Data through Visualization
Understanding Connected Data through Visualization
 
A Few of My Favorite (Python) Things
A Few of My Favorite (Python) ThingsA Few of My Favorite (Python) Things
A Few of My Favorite (Python) Things
 
Introduction to spark
Introduction to sparkIntroduction to spark
Introduction to spark
 
Fancy talk
Fancy talkFancy talk
Fancy talk
 
When RegEx is not enough
When RegEx is not enoughWhen RegEx is not enough
When RegEx is not enough
 
Sorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at SpotifySorry - How Bieber broke Google Cloud at Spotify
Sorry - How Bieber broke Google Cloud at Spotify
 
More expressive types for spark with frameless
More expressive types for spark with framelessMore expressive types for spark with frameless
More expressive types for spark with frameless
 
Inductive Triple Graphs: A purely functional approach to represent RDF
Inductive Triple Graphs: A purely functional approach to represent RDFInductive Triple Graphs: A purely functional approach to represent RDF
Inductive Triple Graphs: A purely functional approach to represent RDF
 
Coscup2021-rust-toturial
Coscup2021-rust-toturialCoscup2021-rust-toturial
Coscup2021-rust-toturial
 
Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...Code is not text! How graph technologies can help us to understand our code b...
Code is not text! How graph technologies can help us to understand our code b...
 
ES6 is Nigh
ES6 is NighES6 is Nigh
ES6 is Nigh
 
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur..."How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
"How was it to switch from beautiful Perl to horrible JavaScript", Viktor Tur...
 

More from Loïc Knuchel

Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...
Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...
Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...
Loïc Knuchel
 
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Loïc Knuchel
 
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Loïc Knuchel
 
Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016
Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016
Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016
Loïc Knuchel
 
FP is coming... le 19/05/2016
FP is coming... le 19/05/2016FP is coming... le 19/05/2016
FP is coming... le 19/05/2016
Loïc Knuchel
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
Loïc Knuchel
 
Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015
Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015
Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015
Loïc Knuchel
 
Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015
Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015
Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015
Loïc Knuchel
 
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Loïc Knuchel
 
Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015
Loïc Knuchel
 
Devoxx 2015, ionic chat
Devoxx 2015, ionic chatDevoxx 2015, ionic chat
Devoxx 2015, ionic chatLoïc Knuchel
 
Ionic HumanTalks - 11/03/2015
Ionic HumanTalks - 11/03/2015Ionic HumanTalks - 11/03/2015
Ionic HumanTalks - 11/03/2015
Loïc Knuchel
 
Ionic bbl le 19 février 2015
Ionic bbl le 19 février 2015Ionic bbl le 19 février 2015
Ionic bbl le 19 février 2015
Loïc Knuchel
 
Des maths et des recommandations - Devoxx 2014
Des maths et des recommandations - Devoxx 2014Des maths et des recommandations - Devoxx 2014
Des maths et des recommandations - Devoxx 2014Loïc Knuchel
 

More from Loïc Knuchel (14)

Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...
Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...
Mutation testing, enfin une bonne mesure de la qualité des tests ?, RivieraDe...
 
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
Comprendre la programmation fonctionnelle, Blend Web Mix le 02/11/2016
 
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
Ionic2, les développeurs web à l'assaut du mobile, BDX I/O le 21/10/2016
 
Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016
Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016
Ionic2 - the raise of web developer, Riviera DEV le 17/06/2016
 
FP is coming... le 19/05/2016
FP is coming... le 19/05/2016FP is coming... le 19/05/2016
FP is coming... le 19/05/2016
 
Programmation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScriptProgrammation fonctionnelle en JavaScript
Programmation fonctionnelle en JavaScript
 
Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015
Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015
Ionic Framework, L'avenir du mobile sera hybride, bdx.io le 16-10-2015
 
Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015
Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015
Ionic, ce n'est pas que de l'UI, meetup PhoneGap le 25-05-2015
 
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
Le développement mobile hybride sort du bois, Ch'ti JUG le 15-04-2015
 
Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015Devoxx 2015, Atelier Ionic - 09/04/2015
Devoxx 2015, Atelier Ionic - 09/04/2015
 
Devoxx 2015, ionic chat
Devoxx 2015, ionic chatDevoxx 2015, ionic chat
Devoxx 2015, ionic chat
 
Ionic HumanTalks - 11/03/2015
Ionic HumanTalks - 11/03/2015Ionic HumanTalks - 11/03/2015
Ionic HumanTalks - 11/03/2015
 
Ionic bbl le 19 février 2015
Ionic bbl le 19 février 2015Ionic bbl le 19 février 2015
Ionic bbl le 19 février 2015
 
Des maths et des recommandations - Devoxx 2014
Des maths et des recommandations - Devoxx 2014Des maths et des recommandations - Devoxx 2014
Des maths et des recommandations - Devoxx 2014
 

Recently uploaded

Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical OperationsEnsuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
OnePlan Solutions
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Paul Brebner
 
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Ortus Solutions, Corp
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
ICS
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
Maitrey Patel
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
chandangoswami40933
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
ShulagnaSarkar2
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
michniczscribd
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
Pedro J. Molina
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Vince Scalabrino
 
Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
WebConnect Pvt Ltd
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
vaishalijagtap12
 
Hyperledger Besu 빨리 따라하기 (Private Networks)
Hyperledger Besu 빨리 따라하기 (Private Networks)Hyperledger Besu 빨리 따라하기 (Private Networks)
Hyperledger Besu 빨리 따라하기 (Private Networks)
wonyong hwang
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
kgyxske
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
gapen1
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
Tier1 app
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
Jhone kinadey
 
What’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 UpdateWhat’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 Update
VictoriaMetrics
 
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
dhavalvaghelanectarb
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
jrodriguezq3110
 

Recently uploaded (20)

Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical OperationsEnsuring Efficiency and Speed with Practical Solutions for Clinical Operations
Ensuring Efficiency and Speed with Practical Solutions for Clinical Operations
 
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
Why Apache Kafka Clusters Are Like Galaxies (And Other Cosmic Kafka Quandarie...
 
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
Strengthening Web Development with CommandBox 6: Seamless Transition and Scal...
 
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA ComplianceSecure-by-Design Using Hardware and Software Protection for FDA Compliance
Secure-by-Design Using Hardware and Software Protection for FDA Compliance
 
ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.ACE - Team 24 Wrapup event at ahmedabad.
ACE - Team 24 Wrapup event at ahmedabad.
 
Computer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdfComputer Science & Engineering VI Sem- New Syllabus.pdf
Computer Science & Engineering VI Sem- New Syllabus.pdf
 
14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision14 th Edition of International conference on computer vision
14 th Edition of International conference on computer vision
 
Beginner's Guide to Observability@Devoxx PL 2024
Beginner's  Guide to Observability@Devoxx PL 2024Beginner's  Guide to Observability@Devoxx PL 2024
Beginner's Guide to Observability@Devoxx PL 2024
 
Orca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container OrchestrationOrca: Nocode Graphical Editor for Container Orchestration
Orca: Nocode Graphical Editor for Container Orchestration
 
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery FleetStork Product Overview: An AI-Powered Autonomous Delivery Fleet
Stork Product Overview: An AI-Powered Autonomous Delivery Fleet
 
Optimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptxOptimizing Your E-commerce with WooCommerce.pptx
Optimizing Your E-commerce with WooCommerce.pptx
 
42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert42 Ways to Generate Real Estate Leads - Sellxpert
42 Ways to Generate Real Estate Leads - Sellxpert
 
Hyperledger Besu 빨리 따라하기 (Private Networks)
Hyperledger Besu 빨리 따라하기 (Private Networks)Hyperledger Besu 빨리 따라하기 (Private Networks)
Hyperledger Besu 빨리 따라하기 (Private Networks)
 
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
一比一原版(sdsu毕业证书)圣地亚哥州立大学毕业证如何办理
 
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
如何办理(hull学位证书)英国赫尔大学毕业证硕士文凭原版一模一样
 
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSISDECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
DECODING JAVA THREAD DUMPS: MASTER THE ART OF ANALYSIS
 
Boost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management AppsBoost Your Savings with These Money Management Apps
Boost Your Savings with These Money Management Apps
 
What’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 UpdateWhat’s New in VictoriaLogs - Q2 2024 Update
What’s New in VictoriaLogs - Q2 2024 Update
 
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024Flutter vs. React Native: A Detailed Comparison for App Development in 2024
Flutter vs. React Native: A Detailed Comparison for App Development in 2024
 
Microsoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptxMicrosoft-Power-Platform-Adoption-Planning.pptx
Microsoft-Power-Platform-Adoption-Planning.pptx
 

Scala bad practices, scala.io 2019

  • 1. 2019 Badr Baddou - Loïc Knuchel @GraalSeeker @loicknuchel
  • 3. Hello ! Badr Baddou Scala dev @ Zeenea @GraalSeeker Loïc Knuchel Tech lead @ Zeenea @loicknuchel Scala FP DDD Property based testing
  • 4. Your next data catalog #Data #Documentation #Glossary #Lineage #Gouvernance
  • 5. @GraalSeeker @loicknuchel Common bad practices ● Do not use null and throw ● Avoid isEmpty / get ● Ban symbols in function names ● Pay attention of primitive types use ● Do not let library conventions leak in your code ● DRY overuse ● Beware of mixing paradigms
  • 6. @GraalSeeker @loicknuchel Primitive obsession ● Primitive types: Int, String, Boolean… ● They do not carry semantics ○ Int, String vs FileSize, Bandwidth, RelPath, Email… ● They are indistinguishable ○ String <=> String vs UserId <!> CommentId ● You don’t known if they were validated ○ String/String vs Email/CheckedEmail ● You have no helper methods ○ path.split(“/”).dropRight(1).mkString(“/”) vs path.getParent()
  • 7. @GraalSeeker @loicknuchel Library- splaining Write a wrapper to protect from library conventions ● Anti corruption layer (DDD) ● Do types conversions ○ null <=> Option ○ throw <=> Try, Either ○ Java collections <=> Scala collections ○ primitive types <=> dedicated types => Type Safety o/ ○ Any <=> ADT ● Paradigm shifts ○ mutable <=> immutable ○ currying ○ sync <=> async (dedicated thread pool)
  • 8. @GraalSeeker @loicknuchel Mixing paradigms class User() { def updatedAt(): Option[Instant] = null def validEmail(): Try[String] = throw new IllegalArgumentException("Email is invalid") }
  • 9. @GraalSeeker @loicknuchel DRY overuse case class User(id: Option[String], name: String, email: Option[String] = None, friends: Seq[String] = Seq(), admin: Boolean = false) case class UserCreation(name: String, email: String) case class User(id: String, name: String, email: String) case class UserFull(id: String, name: String, email: String, friends: Seq[String], admin: Boolean)
  • 10. @GraalSeeker @loicknuchel Real code is (often) a mess ● very long ● inconsitencies ● over generalization (DRY)
  • 11. @GraalSeeker @loicknuchel Conciseness over readability val tuple: (Int, Int) = Map("id" -> ("badr", 13)) .flatMap(e => List(e._2)) .map(_._2 + 1) ./:((0, 0))((a, b) => (a._1 - 1, a._2 + b)) ● Conciseness ≠ Clarity ● No semantics Symbols Tuple Bad naming
  • 12. @GraalSeeker @loicknuchel Solution val tuple: (Int, Int) = Map("id" -> ("badr", 13)) .flatMap(e => List(e._2)) .map(_._2 + 1) ./:((0, 0))((a, b) => (a._1 - 1, a._2 + b)) case class User(name: String, age: Int) val tuple2: (Int, Int) = Map("id" -> User("badr", 13)) .flatMap { case (_, value) => List(value) } .map(user => user.age + 1) .foldLeft((0, 0))((acc, e) => (acc._1 - 1, acc._2 + e)) “The most common things you want to do should be the most concise, while the less common things should be more verbose” Lihayo No symbols Use class not tuples Named pattern matching Named value
  • 13. @GraalSeeker @loicknuchel Powerful Feature misuse final case class Arc(name: String) def main() { Arc("zzz").show() } case class RichArc(value: Arc) { def show() = s"${value.name} is a rich Arc" } implicit def richArc(arc: Arc): RichArc = RichArc(arc) // Problem conversion can apply when not needed def createRichArc(): RichArc = { // conversion not needed here Arc("aaa") }
  • 14. @GraalSeeker @loicknuchel Solution object Syntax { implicit case class EnrichArc(value: Arc) extends AnyVal { def show() = s"${value.name} is a rich Arc" } } def main() { import Syntax._ Arc("zzz").show() }
  • 15. @GraalSeeker @loicknuchel Apply misuse def main(args: Array[String]): Unit = { val arc = Arc("id", "name") } // returns RichArc !!! object Arc { def apply(id: String, name: String): RichArc = { val (in, out) = nodeRepo.getNodes(id).get // throws :( RichArc(id, name, in, out) } } case class Node(id: String, name: String) case class Arc(id: String, name: String) case class RichArc(id: String, name: String, in: Option[Node], out: Option[Node])
  • 16. @GraalSeeker @loicknuchel Solution object Arc { def apply(id: String, name: String): RichArc = { val (in, out) = nodeRepo.getNodes(id).get // throws :( RichArc(id, name, in, out) } } case class NodeRepo() { def getNodes(id: String): Try[(Option[Node], Option[Node])] = ??? } object RichArc { def from(id: String, name: String): Try[RichArc] = { nodeRepo.getNodes(id).map { case (in, out) => RichArc(id, name, in, out) } } }
  • 17. @GraalSeeker @loicknuchel hide and seek implicits object App { def main(args: Array[String]): Unit = { val p: PropertyValue = 1 val q: PropertyValue = true val r: PropertyValue = "toto" } } package object propertyHelpers { implicit def build(v: Any): PropertyValue = PropertyValue(v) } // there should be some implicits here // but no import // where to look??? “Package objects can contain arbitrary definitions. For instance, they are frequently used to hold package-wide implicit conversions.” https://docs.scala-lang.org/tour/package-objects.html
  • 18. @GraalSeeker @loicknuchel Define operator val name: Prop[String] = Prop("name", StrWrap) val score: Prop[Int] = Prop("score", IntWrap) val props = Props( name -> "Jean", score -> 10)
  • 19. @GraalSeeker @loicknuchel How it works? val name: Prop[String] = Prop("name", StrWrap) val score: Prop[Int] = Prop("score", IntWrap) val props = Props( name -> "Jean", score -> 10) case class Props(in: Map[Prop.Name, Prop.Value]) object Props { def apply(in: (Prop.Name, Prop.Value)*): Props = new Props(in.toMap) } // look for implicits case class Prop[A](name:Name, wrap:Wrap[A]) { def ->(value: A): (Prop.Name, Prop.Value) = (name, wrap.encode(value)) }
  • 20.
  • 21.