-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsolid.srp.go
84 lines (68 loc) · 1.45 KB
/
solid.srp.go
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
package solid
import (
"fmt"
"net/url"
"os"
"strings"
)
var entryCount = 0
type Journal struct {
entries []string
}
func (j *Journal) AddEntry(text string) int {
entryCount++
entry := fmt.Sprintf("%d: %s", entryCount, text)
j.entries = append(j.entries, entry)
return entryCount
}
func (j *Journal) RemoveEntry(index int) bool {
if index < 0 || index >= len(j.entries) {
return false
}
j.entries = append(j.entries[:index], j.entries[index+1:]...)
return true
}
func (j *Journal) String() string {
return strings.Join(j.entries, "\n")
}
// separation of concerns
// God Object -> anti-pattern
func (j *Journal) Save(filename string) {
_ = os.WriteFile(filename, []byte(j.String()), 0644)
}
func (j *Journal) Load(filename string) {
//
}
func (j *Journal) LoadFromWeb(url *url.URL) {
//
}
// Alternative approach Single Responsibility Principle
var LineSeparator = "\n"
func SaveToFile(j *Journal, filename string) {
_ = os.WriteFile(filename, []byte(
strings.Join(
j.entries,
LineSeparator,
)), 0644)
}
type Persistence struct {
lineSeparator string
}
func (p *Persistence) SaveToFile(j *Journal, filename string) {
_ = os.WriteFile(filename, []byte(
strings.Join(
j.entries,
p.lineSeparator,
)), 0644)
}
func solidSRP() {
j := Journal{}
j.AddEntry("I cried today")
j.AddEntry("I ate a bug")
fmt.Printf("%s\n", j.String())
//
SaveToFile(&j, "journal.txt")
//
p := Persistence{"\n"}
p.SaveToFile(&j, "journal.txt")
}