-
Notifications
You must be signed in to change notification settings - Fork 1
/
SRP.java
76 lines (62 loc) · 1.78 KB
/
SRP.java
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
// Single Responsibility Principle (SRP)
package solidprinciples.srp;
import java.io.*;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
class Journal
{
private final List<String> entries = new ArrayList<>();
private static int count = 0;
public void addEntry(String text)
{
entries.add("" + (++count) + ": " + text);
}
public void removeEntry(int index)
{
entries.remove(index);
}
@Override
public String toString() {
return String.join(System.lineSeparator(), entries);
}
// here we break SRP
public void save(String filename) throws Exception
{
try (PrintStream out = new PrintStream(filename))
{
out.println(toString());
}
}
public void load(String filename) {}
public void load(URL url) {}
}
// handles the responsibility of persisting objects
class Persistence
{
public void saveToFile(Journal journal,
String filename, boolean overwrite) throws Exception
{
if (overwrite || new File(filename).exists())
try (PrintStream out = new PrintStream(filename)) {
out.println(journal.toString());
}
}
public void load(Journal journal, String filename) {}
public void load(Journal journal, URL url) {}
}
class SRPDemo
{
public static void main(String[] args) throws Exception
{
Journal j = new Journal();
j.addEntry("I cried today");
j.addEntry("I ate a bug");
System.out.println(j);
Persistence p = new Persistence();
String filename = "c:\\Users\\houwa\\desktop\\journal.txt";
p.saveToFile(j, filename, true);
// windows!
Runtime.getRuntime().exec("notepad.exe " + filename);
}
}