-
Notifications
You must be signed in to change notification settings - Fork 0
/
embeddingcomposition.slide
69 lines (37 loc) · 2.09 KB
/
embeddingcomposition.slide
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
Embedding and Composition
Brian Ketelsen
@bketelsen
* Embedding and Composition
Go doesn't do the typical Object Oriented inheritance. Instead Go lets you "borrow" smaller pieces of functionality and embed them into larger types. This is called Composition.
- Composition
cd $GOPATH/src/github.com/gophertrain/material/embeddingcomposition/demos/embedding/
go run main.go
* Composition
Composition works with Interfaces too:
- Embedded Types Interface Example
cd $GOPATH/src/github.com/gophertrain/material/embeddingcomposition/demos/interfaces/
go run main.go
* Composition
Put composition, interfaces and embedding together to get a powerful abstraction:
- Composition, Interfaces, Embedding Example
cd $GOPATH/src/github.com/gophertrain/material/embeddingcomposition/demos/both/
go run main.go
* Important
This concept is crucial to your success as a Go programmer.
Interfaces aren't explicitly declared, they're checked at compile time. You don't have to announce that a Crowbar is a NailPuller, the program won't compile if you try to pass a Crowbar to a function that requires a NailPuller if the Crowbar doesn't implement the PullNail function.
Using interfaces is a confusing change from traditional OO programming concepts. After some time, you'll find them refreshing. You create types that implement behaviors, and create functions that operate on things that implement those behaviors.
Let's go back and look at that example again and reason out loud how we'd do that in Java/Ruby with abstract classes and interfaces.
It's a lot easier to keep the Go version in your head.
* Recap
In Go, we don't create an inheritance chain of functionality:
Transport -> Wheeled -> Car -> Sedan
We create behaviors and apply them to types:
- Behaviors
cd $GOPATH/src/github.com/gophertrain/material/embeddingcomposition/demos/behaviors/
go run main.go
* Exercise
Modify the *behaviors* demo to add another type of transportation, implementing the Storer interface.
- Behaviors
cd $GOPATH/src/github.com/gophertrain/material/embeddingcomposition/exercises/behaviors/
go run main.go