forked from hakimel/reveal.js
-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.html
655 lines (644 loc) · 25.8 KB
/
index.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
<title>Optionated Scala</title>
<link rel="stylesheet" href="css/reveal.css">
<link rel="stylesheet" href="css/theme/black.css">
<!-- Custom styling for this presentation -->
<link rel="stylesheet" href="css/custom.css">
<!-- Theme used for syntax highlighting of code -->
<link rel="stylesheet" href="lib/css/zenburn.css">
<!-- Printing and PDF exports -->
<script>
var link = document.createElement( 'link' );
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = window.location.search.match( /print-pdf/gi ) ? 'css/print/pdf.css' : 'css/print/paper.css';
document.getElementsByTagName( 'head' )[0].appendChild( link );
</script>
</head>
<body>
<div class="reveal">
<div class="slides">
<section>
<h1>Opinionated Scala</h1>
<br/>
<h2 style="font-size: 0.9em;">
Writing opinionated, idiomatic <img style="border: none; background:none; box-shadow:none; height:0.9em; margin: 0; margin-bottom:-0.1em;"src="customresources/scala-logo.png">Scala<br/>
Using Scalas good parts<br/>
Avoiding the bad ones<br/>
Recognizing common mistakes
</h2>
<br/>
<hr/>
<p style="font-size: 0.7em;">Luka Jacobowitz</p>
<p style="font-size: 0.7em;">Jan Schulte</p>
<p style="font-size: 0.7em;">Valentin Willscher</p>
</section>
<section>
<h1>Table of contents</h1>
<ul>
<li>General philosophy</li>
<li>Scalas features
<ul>
<li>Case classes</li>
<li>Traits</li>
<li>Implicits</li>
<li>Pattern matching</li>
<li>About Exceptions</li>
</ul>
</li>
<li>Warts & style</li>
<li>General advice</li>
</ul>
</section>
<section>
<section>
<h1>General philosophy</h1>
Two main things we want to achieve.
<ul class="fragment">
<li>Referential Transparency</li>
<li class="fragment">Type Safety</li>
</ul>
</section>
<section>
<h2>Referential Transparency</h2>
Def: "Referential transparency means exchanging any term for another term that refers to the same entity does not change the program."
<p class="fragment">Lets us and the compiler reason with our code at a much greater level</p>
</section>
<section>
<pre><code data-trim data-noescape class="scala">
def add(a: Int, b: Int): Int {
launchTheNukes()
a + b
}
add(1, 3) * add(1, 3) //let’s inline this!
val x = add(1,3)
x * x //whoops! We changed the program!
</code></pre>
</section>
<section>
<h2>Type Safety</h2>
Complete Type Safety: A program that compiles must always be a valid program (i.e. no runtime exceptions).
<p class="fragment">Scala's Type System is extremely expressive! Let the compiler work for you!</p>
</section>
<section>
<pre><code data-trim data-noescape class="scala">
scala> val i2: Int Refined Positive = -5
<console>:22: error: Predicate failed: (-5 > 0).
val i2: Int Refined Positive = -5
^
scala> val u1: String Refined Url = "htp://example.com"
<console>:38: error: Url predicate failed: unknown protocol: htp
val u1: String Refined Url = "htp://example.com"
^
</code></pre>
</section>
<section>Idiomatic but not dogmatic!</section>
</section>
<section>
<section>
<h1>Case classes</h1>
<ul>
<li>"Java-DTOs" - simple data bags</li>
<li>Must never contain state</li>
<li>Should never depend on other types unless domain rules tell so</li>
<li>Anemic Domain Model, not Rich Domain Model (= classical OOP)</li>
<li>Should never throw Exceptions, not even on instantiation</li>
</ul>
</section>
<section>
<h2>Containing state</h2>
<pre><code data-trim data-noescape class="scala">
case class User(
name: UserName,
val lastLogins: mutable.Seq[DateTime],
var failedLogins: Int
)
</code></pre>
</section>
<section>
<h2>Depending on other entities</h2>
Not so good:
<pre><code data-trim data-noescape class="scala">
case class Pet(name: String) //defined somewhere else
case class User(name: String) {
def hasSameNameAs(pet: Pet) = this.name == pet.name
}
</code></pre>
Better:
<pre><code data-trim data-noescape class="scala">
case class Pet(name: String, typ: PetType) //somewhere else
case class User(name: String, var failedLogins: Int)
object User {
implicit class UserOps(user: User) {
def hasSameNameAs(pet: Pet) = user.name == pet.name
}
}
</code></pre>
</section>
</section>
<section>
<section>
<h1>Traits</h1>
Traits in different flavours
<ul>
<li>Sealed traits for sumtypes</li>
<li>"interface" inheritance</li>
<li>Encoding typeclasses</li>
<li>Traits without implementation</li>
<li>Dependency injection, cake pattern</li>
</ul>
</section>
<section>
<h2>Sealed traits for sumtypes</h2>
<pre><code data-trim data-noescape class="scala">
sealed trait Shape
final case class Circle (radius: Double) extends Shape
final case class Rectangle(width: Int, height: Int) extends Shape
final case object Rheinturm extends Shape
final case object KoelnerDom extends Shape
</code></pre>
<p class="fragment">Gives us...
<ul class="fragment">
<li>Pattern matching safety (exhaustive warnings)</li>
<li>Easy to comprehend description of business domain</li>
</ul>
</p>
<p class="fragment">Important:
<ul class="fragment">
<li>The sealed keyword is essential</li>
<li>Avoid functionality</li>
</ul>
</p>
</section>
<section>
<h2>"interface" inheritance</h2>
<pre><code data-trim data-noescape class="scala">
sealed trait LogMessage {
def msg: String
}
case class InfoMessage(msg: String) extends LogMessage
case class WarnMessage(msg: String) extends LogMessage
case class ErrorMessage(msg: String) extends LogMessage
</code></pre>
<pre class="fragment"><code data-trim data-noescape class="scala">
trait Drawable {
def asImage: JPG
}
case class Circle(...) extends Drawable {
override def asImage: JPG = ???
}
</code></pre>
<p class="fragment">'Okayish' when writing application code but not library code...</p>
</section>
<section>
<h2>encode typeclasses</h2>
<ul>
<li>Typeclasses are a powerfull concept.</li>
<li>They are a bit more boilerplate than inheritance.</li>
<li>Always use typeclasses when writing libraries or when inheritance gets more complex.</li>
</ul>
</section>
<section>
<h2>typeclasses for libraries</h2>
Bad logging library:
<pre><code data-trim data-noescape class="scala">
trait StringSerializeable {
def serialized: String
}
def log[A <: StringSerializeable](obj: A) =
writeToLogFile( obj.serialized )
</code></pre>
<p class="fragment">
Good logging library:
<pre class="fragment"><code data-trim data-noescape class="scala">
trait StringSerializer {
def serialize[A](obj: A): String
}
def log[A: StringSerializer](obj: A) =+
writeToLogFile( implicitly[StringSerializer].serialize(obj) )
</code></pre>
</p>
</section>
<section>
<h2>zero implementation traits</h2>
<ul>
<li>They have nothing extending them</li>
<li>They are never intantiated</li>
<li class="fragment">Used for typelevel programming</li>
<li class="fragment">Used for phantom types</li>
</ul>
</section>
<section>
<h2>DI / cake pattern</h2>
Just no. Don't do that. Period.<br>
Use Constructor injection instead, or Macwire if you are really lazy.<br>
{insert bakery-of-doom image here}
</section>
<section>
<h2>abstract classes</h2>
<ul>
<li>One can extend many traits but only 1 abstract class</li>
<li>They can have constructor parameters</li>
<li>Generally use traits unless you need abstract classes</li>
</ul>
<p class="fragment">
This is an okayish usage to avoid boilerplate:
<pre class="fragment"><code data-trim data-noescape class="scala">
sealed abstract class ServiceError(msg: String)
case object Timeout extends ServiceError("Request took too long")
case object InvalidResponse extends ServiceError("Parse-error")
</code></pre>
<p/>
</section>
</section>
<section>
<section>
<h1>Implicits</h1>
What happens when we try to compile and execute this code:
<iframe height="200" frameborder="0" style="width: 100%; overflow: hidden;" src="https://embed.scalafiddle.io/embed?sfid=IunxWmZ/2&theme=dark&layout=v50"></iframe>
<!--
<pre><code data-trim data-noescape class="scala">
implicit val petNames = List("Cat", "Dog", "Dolphin")
def logPetName(petName: String) = println(x)
val galacticConstant: Int = 42
logPetName(galacticConstant)
</code></pre>
-->
<ul class="fragment">
<li>Avoid implicits, except for wellknown patterns</li>
<li>The more specific the implicit type the better</li>
</ul>
</section>
<section>
<h2>Implicit methods</h2>
Avoid implicit methods except for
<ul>
<li>Extending functionality on existing types (implicit class pattern)</li>
<li>Methods with only implicit parameters (typelevel programming)</li>
</ul>
</section>
<section>
<h2>Implicit methods examples</h2>
<div class="fragment">
Bad:
<pre><code data-trim data-noescape class="scala">
implicit def charList(s: String): List[Char] = ???
</code></pre>
</div>
<div class="fragment">
Good:
<pre><code data-trim data-noescape class="scala">
class StringOps(s: String) {
def toCharList: List[Char] = ???
}
implicit def (s: String): StringOps = new StringOps(s)
</code></pre>
</div>
<div class="fragment">
...or even better:
<pre><code data-trim data-noescape class="scala">
implicit class StringOps(s: String) {
def toCharList: List[Char] = ???
}
</code></pre>
</div>
</section>
<section>
<h2>Implicit parameters</h2>
<ul>
<li>There is only one sane usage: typeclasses</li>
<li>That's it. Nothing more. Period. (Or is there more?)</li>
<li>Don't use it to pass "configurations" or "contexts" down the call chain!</li>
</ul>
<br>
<p class="fragment">
It's common practice to pass an implicit ExecutionContext.<br>
This is a code smell and can mostly be solved better.
</p>
</section>
<section>
<h2>Implicit parameters</h2>
<div class="fragment">
Bad:
<pre><code data-trim data-noescape class="scala">
def greetUser(name: UserName)(implicit lang: Language) = ???
</code></pre>
</div>
<div class="fragment">
Worse:
<pre><code data-trim data-noescape class="scala">
def allUsers(repository: UserRepository)
(implicit ec: ExecutionContext) = ???
</code></pre>
</div>
<div class="fragment">
Doomed!
<pre><code data-trim data-noescape class="scala">
def getAllUsers(repository: UserRepository)
(implicit ec: ExecutionContext, timeoutLimit: Long) = ???
</code></pre>
</div>
</section>
<section>
<h2>Implicit parameters<br> the good parts</h2>
Good:
<pre><code data-trim data-noescape class="scala">
def serialize[A](obj: A)
(implicit si: SerializeInstructions[A]) = ???
</code></pre>
<div class="fragment">
Better:
<pre><code data-trim data-noescape class="scala">
def serialize[A: SerializeInstructions](obj: A) = ???
</code></pre>
</div>
</section>
</section>
<section>
<section>
<h1>Pattern matching</h1>
<ul>
<li>Powerful but unsafe in many cases</li>
<li>Sometimes overused - if/else is not generally bad!</li>
<li>Don't write unsafe pattern matches, ever.<br>You don't have to</li>
</ul>
</section>
<section>
<h2>Pattern matching - overused</h2>
<pre><code data-trim data-noescape class="scala">
birthyear match {
case 1989 => println("This is the best year")
case 2020 => println("Are you from the Future[_]?!")
}
</code></pre>
<div class="fragment">
Do we really need pattern matching here? Let's see...
<pre><code data-trim data-noescape class="scala">
if(birthyear == 1989)
println("This is the best year")
else if(birthyear == 2020)
println("Are you from the Future[_]?!")
</code></pre>
One can immediately see that this might be unsafe because we have not covered all cases.
</div>
</section>
<section>
<h2>Safe pattern matching</h2>
Using the <i>-Xfatal-warnings</i> compiler-flag,<br>
it is always safe to pattern match on...
<ul>
<li>Primitives (Int, Boolean, String, ...) within case classes</li>
<li>Sealed traits of (final) case classes</li>
</ul>
<p>
Everything else can make pattern matching unsafe<br>
Including guard-conditions<br>
But: pattern matching while using a default case is always safe, obviously
</p>
</section>
<section>
<h2>pattern matching examples<br>safe cases</h2>
<pre style="font-size: 0.4em;" class="fragment"><code data-trim data-noescape class="scala">
true match { case true => ??? }
//Error: It would fail on the following input: false
</code></pre>
<pre style="font-size: 0.4em;" class="fragment"><code data-trim data-noescape class="scala">
sealed trait Fruit
case class Grape (seedWeight: Option[Double]) extends Fruit
case class Banana(length: Float) extends Fruit
case class Apple (seeds: List[Seed]) extends Fruit
someFruit match {
case Grape (_) => ???
case Banana(_) => ???
}
//Error: It would fail on the following input: Apple(_)
</code></pre>
<pre style="font-size: 0.4em;" class="fragment"><code data-trim data-noescape class="scala">
someFruit match {
case Grape (_) => ???
case Banana(20.05) => ???
case Apple (_) => ???
}
//Error: It would fail on the following input:
//Banana((x: Float forSome x not in 20.05))
</code></pre>
</section>
<section>
<h2>pattern matching examples<br>guards</h2>
Unsafe when using guards:
<pre><code data-trim data-noescape class="scala">
someFruit match {
case Grape (_) => ???
case Banana(length) if length > 20 => ???
case Apple (_) => ???
}
</code></pre>
<div class="fragment">
Make it safe with default case:
<pre><code data-trim data-noescape class="scala">
someFruit match {
case Grape (_) => ???
case Banana(length) if length > 20 => ???
case Apple (_) => ???
case _ => ???
}
</code></pre>
</div>
</section>
<section>
<h2>pattern matching examples<br>nested</h2>
Safe nested pattern matching:
<pre><code data-trim data-noescape class="scala">
//case class Grape(seedWeight: Option[Double]) extends Fruit
someFruit match {
case Grape (Some(weight)) => ???
case Banana(_) => ???
case Apple (_) => ???
}
</code></pre>
<div class="fragment">
You can pattern match as deep as you want,<br>
as long as every nesting-level applies to these rules!
</div>
</section>
<section>
<h2>pattern matching examples<br>nested</h2>
Is this safe?
<pre style="font-size: 0.4em;"><code data-trim data-noescape class="scala">
//Remember: case class Apple(seeds: List[Seed]) extends Fruit
someFruit match {
case Grape (_) => ???
case Banana(_) => ???
case Apple (List(Seed(), Seed(), Seed())) => ???
}
</code></pre>
<div class="fragment">
It will fail with a MatchError at runtime! Better:<br>
<pre style="font-size: 0.4em;"><code data-trim data-noescape class="scala">
someFruit match {
case Grape (_) => ???
case Banana(_) => ???
case Apple (Seed() :: Seed() :: Seed() :: Nil) => ???
}
//Compiler:
//match may not be exhaustive.
//It would fail on the following inputs:
//Apple(List(_)), Apple(List(_, _)), Apple(List(_, _, _, _)), Apple(Nil)
</code></pre>
</div>
</section>
</section>
<section>
<section>
<h2>Exceptions</h2>
Exceptions indicate either...
<ul class="fragment">
<li>Technical errors (e.g. NullPointerException)</li>
<li class="fragment">Fatal errors (e.g. StackOverFlowException)</li>
<li class="fragment">Domain errors (e.g. NumberFormatException)</li>
</ul>
<p class="fragment">We usually want to encode all non-fatal errors in the type system (e.g. with the Either type). That way we can never forget to handle them.</p>
<p class="fragment">If you need to work with a library that throws Exceptions use Try (upper- not lowercase)</p>
</section>
<section>
<h3>Bad</h3>
<pre style="font-size: 0.4em;"><code data-trim data-noescape class="scala">
def asyncGetUser(userId): Future[User] = ???
val userResult = Await(asyncGetUser(someId), 20.seconds)
userResult match {
case Success(user) => println("wuh, user found!")
case Failure(ResponseTimeoutException()) => println("Timed out!")
case Failure(UserNotFound(userId)) => println("Could not find user")
case Failure(UserParseError(jsonError)) => println("Could find user but not parse it")
case Failure(throwable) => println("Uh oh, something went wrong. Maybe the Thread was interrupted OR maybe we did forget to handle a domain error? Who knows...")
}
</code></pre>
</section>
<section>
<h3>Better</h3>
<pre style="font-size: 0.4em;"><code data-trim data-noescape class="scala">
def asyncGetUser(userId): Future[Either[DomainError, User]] = ???
val userResult = Await(asyncGetUser(someId), 20.seconds)
userResult match {
//Technically everything went well. We can now check for domain errors.
case Success(domainResult) => domainResult match {
case Right(user) => println("wuh, user found!")
case Left(ResponseTimeoutException) => println("Timed out!")
case Left(UserNotFound(userId)) => println("Could not find user")
case Left(UserParseError(jsonError)) => println("Could find user but not parse it")
}
//Only technical error
case Failure(throwable) => println("Uh oh, something went wrong. Maybe the Thread was interrupted but it can't be a domain error that we forgot to handle!")
}
</code></pre>
</section>
</section>
<section>
<h1>Warts & style</h1>
<section>
<h2 class="fragment">Pitfall partial functions</h2>
<ul>
<li class="fragment">Never use `Option.get`...</li>
<li class="fragment">...use `getOrElse`, `map` or literally anything else.</li>
<li class="fragment">Do NOT use `List.apply`, e.g. `val x = List(5)`</li>
<li class="fragment">... use `lift` instead. </li>
<li class="fragment">Same goes for `head`, there use `headOption`</li>
</ul>
</section>
<section>
<h2>Pitfall partial functions</h2>
<ul>
<li class="fragment"><pre style="width=100%"><code class="scala">list map { case Person(name) => save(name) }</code></pre></li>
<li class="fragment"><pre style="width=100%"><code class="scala">list collect { case Person(name) => save(name) }</code></pre></li>
</ul>
</section>
<section>
<h2>Functions on functors</h2>
<ul>
<li class="fragment"><pre style="width=100%"><code class="scala">def transformOption(input:Option[Int]):Option[Int]</code></pre></li>
<li class="fragment"><pre style="width=100%"><code class="scala">def transform(input:Int):Int</code></pre></li>
<li class="fragment"><pre style="width=100%"><code class="scala">myOption.map(transform)</code></pre></li>
</ul>
</section>
<section>
<h2>Functions on functors</h2>
<ul>
<li class="fragment"><pre style="width=100%"><code class="scala">def transformEachSingleElement(input:List[Int]):List[Int]</code></pre></li>
<li class="fragment"><pre style="width=100%"><code class="scala">def transform(input:Int):Int</code></pre></li>
<li class="fragment"><pre style="width=100%"><code class="scala">myList.map(transform)</code></pre></li>
</ul>
</section>
<section>
<h2>Further suggestions</h2>
<ul>
<li class="fragment">Avoid using `Seq`, as it default to the mutable version</li>
<li class="fragment">Don't await Futures unless you want to block the thread on purpose!</li>
<li class="fragment">Single file only for ADTs (= case class model)</li>
</ul>
</section>
<section>
<h2>Further suggestions</h2>
<ul>
<li class="fragment">Public methods and vals should have a type annotation</li>
<li class="fragment">You might want to try Scapegoat or WartRemover to help</li>
</ul>
</section>
</section>
<section>
<h1>General advice</h1>
<section>
<h2>Libraries & frameworks</h2>
<ul>
<li class="fragment">Prefer Scala libraries over Java libraries</li>
<li class="fragment">Use strongly typed, functional libraries</li>
<li class="fragment"><a href="http://www.typelevel.org">Typelevel</a> is a good starting point</li>
<li class="fragment">Avoid writing your own framework!</li>
</ul>
</section>
<section>
<h2>Keep it simple, stupid!</h2>
<ul>
<li class="fragment">Scala is a powerful weapon!</li>
<li class="fragment">Do you really need Akka? Spark?</li>
<li class="fragment">Avoid macros!</li>
<li class="fragment">Might shapeless be the option?</li>
</ul>
</section>
<section>
<h2>Separation of concerns</h2>
<ul>
<li class="fragment">DRY is overrated</li>
<li class="fragment">Do one thing and do it well!</li>
<li class="fragment">From functions to architecture</li>
</ul>
</section>
<section>
<ul>
<img class="fragment" src="customresources/architecture.png"></img>
</ul>
</section>
</section>
</div>
</div>
<script src="lib/js/head.min.js"></script>
<script src="js/reveal.js"></script>
<script>
// More info about config & dependencies:
// - https://github.com/hakimel/reveal.js#configuration
// - https://github.com/hakimel/reveal.js#dependencies
Reveal.initialize({
history: true,
dependencies: [
{ src: 'plugin/markdown/marked.js' },
{ src: 'plugin/markdown/markdown.js' },
{ src: 'plugin/notes/notes.js', async: true },
{ src: 'plugin/highlight/highlight.js', async: true, callback: function() { hljs.initHighlightingOnLoad(); } }
]
});
</script>
</body>
</html>