Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code | Sign in
(130)

Side by Side Diff: 2014/go4java.slide

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

Powered by Google App Engine
RSS Feeds Recent Issues | This issue
This is Rietveld f62528b