Text file
talks/2014/go4java.slide
1 Go for Javaneros (Javaïstes?)
2 #go4java
3
4 Francesc Campoy
5 Gopher and Developer Advocate
6 Google
7 @francesc
8 campoy@golang.org
9
10 * What is Go?
11
12 Go is an open-source programming language
13
14 - created at Google,
15 - to solve Google-scale problems.
16
17 .image go4java/img/gopher.jpg 450 _
18
19 * Who uses Go?
20
21 Google:
22
23 - YouTube
24 - dl.google.com
25
26 Others:
27
28 - dotCloud (Docker)
29 - SoundCloud
30 - Canonical
31 - CloudFlare
32 - Mozilla
33 - ...
34
35 [[/wiki/GoUsers][go.dev/wiki/GoUsers]]
36
37 * Who uses Go?
38
39 .image go4java/img/trends.png _ 800
40
41 .caption Google Trends for [[http://www.google.com/trends/explore#q=golang][golang]]
42
43 * Why Go?
44
45 * Simplicity
46
47 Minimal design
48
49 .image go4java/img/perfection.jpg
50
51 * Consistency
52
53 Orthogonal features
54
55 .image go4java/img/lego.jpg 400 _
56
57 .caption By Kenny Louie from Vancouver, Canada [[http://creativecommons.org/licenses/by/2.0][CC-BY-2.0]], via Wikimedia Commons
58
59 * Readability
60
61 “The ratio of time spent reading (code) versus writing is well over 10 to 1 ... (therefore) making it easy to read makes it easier to write.”
62 ― Robert C. Martin
63
64 .image go4java/img/piet.png 500 600
65
66 * Safety
67
68 Type safety, no buffer overflows, no pointer arithmetic.
69
70 .image go4java/img/baby.jpg 500 500
71
72 * Built-in concurrency features
73
74 “In a concurrent world, imperative is the wrong default!” - Tim Sweeney
75
76 Communicating Sequential Processes - Hoare (1978)
77
78 .image go4java/img/conc.jpg _ 1000
79
80 * Speed
81
82 .image go4java/img/fast.jpg 500 _
83
84 * Let's dive in
85
86 * Go and Java common aspects
87
88 Go and Java are
89
90 - object oriented
91
92 - garbage collected
93
94 - statically typed
95
96 - part of the C family
97
98 * Object oriented flavors
99
100 Go is Object Oriented, but doesn't have the keywords:
101
102 - `class`,
103 - `extends`, or
104 - `implements`.
105
106 * All types are created equal
107
108 * Go types
109
110 - primitive types
111
112 int, uint, int8, uint8, ...
113 bool, string
114 float32, float64
115 complex64, complex128
116
117 - structs
118
119 struct {
120 Name string
121 Age int
122 }
123
124 - slices and arrays
125
126 []int, [3]string, []struct{ Name string }
127
128 - maps
129
130 map[string]int
131
132 * Kinds of types (continued)
133
134 - pointers
135
136 *int, *Person
137
138 - functions
139
140 func(int, int) int
141
142 - channels
143
144 chan bool
145
146 - interfaces
147
148 interface {
149 Start()
150 Stop()
151 }
152
153 * Type declarations
154
155 type [name] [specification]
156
157 `Person` is a `struct` type.
158
159 type Person struct {
160 name string
161 age int
162 }
163
164 `Celsius` is a `float64` type.
165
166 type Celsius float64
167
168 * Function declarations
169
170 func [name] ([params]) [return value]
171 func [name] ([params]) ([return values])
172
173 A sum function:
174
175 func sum(a int, b int) int {
176 return a + b
177 }
178
179 A function with multiple returned values:
180
181 func div(a, b int) (int, int)
182 return a / b, a % b
183 }
184
185 Made clearer by naming the return values:
186
187 func div(den, div int) (q, rem int)
188 return a / b, a % b
189 }
190
191 * Method declarations
192
193 func ([receiver]) [name] ([params]) ([return values])
194
195 A method on a struct:
196
197 func (p Person) Major() bool {
198 return p.age >= 18
199 }
200
201 But also a method on a `float64`:
202
203 func (c Celsius) Freezing() bool {
204 return c <= 0
205 }
206
207 _Constraint:_ Methods can be defined *only* on types declared in the same package.
208
209 // This won't compile
210 func (s string) Length() int { return len(s) }
211
212 * Wait, pointers?
213
214 Use `&` to obtain the address of a variable.
215
216 a := "hello"
217 p := &a
218
219 Use `*` to dereference the pointer.
220
221 fmt.Print(*p + ", world")
222
223 No pointer arithmetic, no pointers to unsafe memory.
224
225 a := "hello"
226 p := &a
227
228 p += 4 // no, you can't
229
230 * Why pointers?
231
232 Control what you pass to functions.
233
234 - passing values, no side-effects:
235
236 func double(x int) {
237 x *= 2
238 }
239
240 - passing pointers: side-effects possible:
241
242 func double(x *int) {
243 *x *= 2
244 }
245
246 Control your memory layout.
247
248 - compare []Person and []*Person
249
250 * Method declarations on pointers
251
252 Receivers behave like any other argument.
253
254 Pointers allow modifying the pointed receiver:
255
256 func (p *Person) IncAge() {
257 p.age++
258 }
259
260 The method receiver is a copy of a pointer (pointing to the same address).
261
262 Method calls on nil receivers are perfectly valid (and useful!).
263
264 func (p *Person) Name() string {
265 if p == nil {
266 return "anonymous"
267 }
268 return p.name
269 }
270
271 * Interfaces
272
273 * Interfaces
274
275 An interface is a set of methods.
276
277 In Java:
278
279 interface Switch {
280 void open();
281 void close();
282 }
283
284 In Go:
285
286 type OpenCloser interface {
287 Open()
288 Close()
289 }
290
291 * It's all about satisfaction
292
293 Java interfaces are satisfied *explicitly*.
294
295 Go interfaces are satisfied *implicitly*.
296
297 .image //upload.wikimedia.org/wikipedia/commons/thumb/2/29/Rolling_Stones_09.jpg/512px-Rolling_Stones_09.jpg _ 512
298
299 .caption Picture by Gorupdebesanez [[http://creativecommons.org/licenses/by-sa/3.0][CC-BY-SA-3.0]], via [[http://commons.wikimedia.org/wiki/File%3ARolling_Stones_09.jpg][Wikimedia Commons]]
300
301 * Go: implicit satisfaction
302
303 _If_a_type_defines_all_the_methods_of_an_interface,_the_type_satisfies_that_interface._
304
305 Benefits:
306
307 - fewer dependencies
308 - no type hierarchy
309 - organic composition
310
311 * Structural subtyping
312
313 Think static duck typing, verified at compile time.
314
315 .image go4java/img/duck.jpg 500 500
316
317 * FuncDraw: an example on interfaces
318
319 .image go4java/img/funcdraw.png 500 700
320
321 * FuncDraw: package parser
322
323 Package `parse` provides a parser of strings into functions.
324
325 func Parse(text string) (*Func, error) { ... }
326
327 `Func` is a struct type, with an `Eval` method.
328
329 type Func struct { ... }
330
331 func (p *Func) Eval(x float64) float64 { ... }
332
333 * FuncDraw: package draw
334
335 Package draw generates images given a function.
336
337 func Draw(f *parser.Func) image.Image {
338 for x := start; x < end; x += inc {
339 y := f.Eval(x)
340 ...
341 }
342 }
343
344 `draw` depends on `parser`
345
346 - makes testing hard
347
348 Let's use an interface instead
349
350 type Evaluable interface {
351 Eval(float64) float64
352 }
353
354 func Draw(f Evaluable) image.Image { ... }
355
356 * Inheritance vs composition
357
358 * Inheritance vs composition
359
360 Lots of articles have been written about the topic.
361
362 In general, composition is preferred to inheritance.
363
364 Lets see why.
365
366 * Runner
367
368 .code go4java/BadInheritance.java /START_RUNNER/,/END_RUNNER/
369
370 * RunCounter is-a Runner that counts
371
372 .code go4java/BadInheritance.java /START_COUNTING/,/END_COUNTING/
373
374 * Let's run and count
375
376 What will this code print?
377
378 .code go4java/BadInheritance.java /START_MAIN/,/END_MAIN/
379
380 Of course, this prints:
381
382 running one
383 running two
384 running three
385 my runner ran 6 tasks
386
387 Wait! How many?
388
389 * My runner ran 6 tasks? Six?
390
391 Inheritance causes:
392
393 - weak encapsulation,
394 - tight coupling,
395 - surprising bugs.
396
397 .image go4java/img/badinheritance.png
398
399 * Solution: use composition
400
401 .code go4java/Composition.java /START_COUNTING/,/BREAK_COUNTING/
402
403 * Solution: use composition (continued)
404
405 .code go4java/Composition.java /BREAK_COUNTING/,/END_COUNTING/
406
407 * Solution: use composition (continued)
408
409 *Pros*
410
411 - The bug is gone!
412 - `Runner` is completely independent of `RunCounter`.
413 - The creation of the `Runner` can be delayed until (and if) needed.
414
415 *Cons*
416
417 - We need to explicitly define the `Runner` methods on `RunCounter`:
418
419 public String getName() { return runner.getName(); }
420
421 - This can cause lots of repetition, and eventually bugs.
422
423 * There's no inheritance in Go
424
425 * There's no inheritance in Go
426
427 Let's use composition directly:
428
429 # .code go4java/runner/runner.go /type Task/,/END_TASK/
430
431 .code go4java/runner/runner.go /type Runner/,/END_RUNNER/
432
433 All very similar to the Java version.
434
435 * RunCounter
436
437 `RunCounter` has a `Runner` field.
438
439 .code go4java/runner/runner.go /type RunCounter/,
440
441 * Composition in Go
442
443 Same pros and cons as the composition version in Java.
444
445 We also have the boilerplate to proxy methods from `Runner`.
446
447 .code go4java/runner/runner.go /runner.Name/
448
449 But we can remove it!
450
451 * Struct embedding
452
453 Expressed in Go as unnamed fields in a struct.
454
455 It is still *composition*.
456
457 The fields and methods of the embedded type are defined on the embedding type.
458
459 Similar to inheritance, but the embedded type doesn't know it's embedded.
460
461 * Example of struct embedding
462
463 Given a type `Person`:
464
465 .code go4java/embedsample.go /Person/,/Hi/
466
467 We can define a type `Employee` embedding `Person`:
468
469 .code go4java/embedsample.go /Employee/,/}/
470
471 All fields and methods from `Person` are available on `Employee`:
472
473 .code go4java/embedsample.go /var/,/Introduce/
474
475 * Struct embedding
476
477 .code go4java/runner/embed.go /type RunCounter2/,
478
479 * Is struct embedding like inheritance?
480
481 No, it is better!
482
483 It is composition.
484
485 - You can't reach into another type and change the way it works.
486
487 - Method dispatching is explicit.
488
489 It is more general.
490
491 - Struct embedding of interfaces.
492
493 * Is struct embedding like inheritance?
494
495 Struct embedding is selective.
496
497 .code go4java/writecounter.go /WriteCounter/,/MAIN/
498
499 WriteCounter can be used with any `io.ReadWriter`.
500
501 .play go4java/writecounter.go /func main/,/^}/
502
503 * Easy mocking
504
505 What if we wanted to fake a part of a `net.Conn`?
506
507 type Conn interface {
508 Read(b []byte) (n int, err error)
509 Write(b []byte) (n int, err error)
510 Close() error
511 LocalAddr() Addr
512 RemoteAddr() Addr
513 SetDeadline(t time.Time) error
514 SetReadDeadline(t time.Time) error
515 SetWriteDeadline(t time.Time) error
516 }
517
518 I want to test `handleCon`:
519
520 .code go4java/loopback.go /handleCon/
521
522 - We could create a `fakeConn` and define all the methods of `Conn` on it.
523
524 - But that's a lot of boring code.
525
526 * Struct embedding of interfaces
527
528 _WARNING_:_Cool_stuff_
529
530 If a type T has an embedded field of a type E, all the methods of E will be defined on T.
531
532 Therefore, if E is an interface T satisfies E.
533
534 * Struct embedding of interfaces (continued)
535
536 We can test `handleCon` with the `loopBack` type.
537
538 .code go4java/loopback.go /loopBack/,/^}/
539
540 Any calls to the methods of `net.Conn` will fail, since the field is nil.
541
542 We redefine the operations we support:
543
544 .code go4java/loopback.go /Read/,
545
546 * Concurrency
547
548 * Concurrency
549
550 It is part of the language, not a library.
551
552 Based on two concepts:
553
554 - goroutines: lightweight threads
555 - channels: typed pipes used to communicate and synchronize between goroutines
556
557 So cheap you can use them whenever you want.
558
559 .image go4java/img/funnelin.jpg 300 700
560
561 * Sleep and talk
562
563 .code go4java/conc1.go /sleepAndTalk/,/^}/
564
565 We want a message per second.
566
567 .play go4java/conc1.go /func main/,/^}/
568
569 What if we started all the `sleepAndTalk` concurrently?
570
571 Just add `go`!
572
573 * Concurrent sleep and talk
574
575 .play go4java/conc2.go /func main/,/^}/
576
577 That was fast ...
578
579 When the `main` goroutine ends, the program ends.
580
581 * Concurrent sleep and talk with more sleeping
582
583 .play go4java/conc3.go /func main/,/^}/
584
585 But synchronizing with `Sleep` is a bad idea.
586
587 * Communicating through channels
588
589 `sleepAndTalk` sends the string into the channel instead of printing it.
590
591 .code go4java/chan.go /sleepAndTalk/,/^}/
592
593 We create the channel and pass it to `sleepAndTalk`, then wait for the values to be sent.
594
595 .play go4java/chan.go /func main/,/^}/
596
597 * Let's count on the web
598
599 We receive the next id from a channel.
600
601 .code go4java/goodcounter.go /nextID/,/^}/
602
603 We need a goroutine sending ids into the channel.
604
605 .play go4java/goodcounter.go /func main/,/^}/
606
607 [[http://localhost:8080/next]]
608
609 * Let's fight!
610
611 `select` allows us to chose among multiple channel operations.
612
613 .play go4java/battle.go /battle/,/^}/
614
615 Go - [[http://localhost:8080/fight?usr=go]]
616 Java - [[http://localhost:8080/fight?usr=java]]
617
618 * Chain of gophers
619
620 .image go4java/img/chain.jpg
621
622 Ok, I'm just bragging here
623
624 * Chain of gophers
625
626 .play go4java/goroutines.go /func f/,
627
628 * Concurrency is very powerful
629
630 And there's lots to learn!
631
632 - [[/talks/2012/concurrency.slide#1][Go Concurrency Patterns]], by Rob Pike
633 - [[/talks/2013/advconc.slide#1][Advanced Concurrency Patterns]], by Sameer Ajmani
634 - [[/talks/2012/waza.slide#1][Concurrency is not Parallelism]], by Rob Pike
635
636 .image go4java/img/busy.jpg
637
638 * In conclusion
639
640 Go is simple, consistent, readable, and fun.
641
642 All types are equal
643
644 - methods on any type
645
646 Implicit interfaces
647
648 - Structural typing
649 - Less dependencies
650 - Code testable and reusable
651
652 Use composition instead of inheritance
653
654 - Struct embedding to remove boilerplate.
655 - Struct embedding of interfaces to satisfy them fast.
656
657 Concurrency is awesome, and you should check it out.
658
659 * What to do next?
660
661 Learn Go on your browser with [[/tour/][go.dev/tour]]
662
663 Find more about Go on [[/][go.dev]]
664
665 Join the community at [[https://groups.google.com/forum/#!forum/Golang-nuts][golang-nuts]]
666
667 Link to the slides [[/talks/2014/go4java.slide]]
668
View as plain text