-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathSrp.cs
80 lines (70 loc) · 1.73 KB
/
Srp.cs
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
using System;
using System.IO;
namespace Solid.SingleResponsibility
{
class Srp : IPrinciple
{
public string Principle()
{
return "Single Responsibility";
}
}
// Violating the Single Responsibility Principle
internal class Customer
{
// This Add method does too much,
// it shouldnt know how to write to the log and add a customer
public void Add(Database db)
{
try
{
db.Add();
}
catch (Exception ex)
{
File.WriteAllText(@"C:\Error.txt", ex.ToString());
}
}
}
// Good Way, not violating the single responsibility principle
// Now we abstract the logger, so its just writing the error.
class CustomerBetter
{
private FileLogger logger = new FileLogger();
public void Add(Database db)
{
try {
db.Add();
}
catch (Exception ex)
{
logger.Handle(ex.ToString());
}
}
}
internal class FileLogger
{
public void Handle(string error)
{
File.WriteAllText(@"C:\Error.txt", error);
}
}
// Even Better Way
// Even better, the customer only knows how to add, and we
// wrap the add method in an error handler.
// @see Utilities/Customer
class Wrapper
{
public void HandleAdd(FileLogger logger, Database db, Customer customer)
{
try
{
customer.Add(db);
}
catch (Exception error)
{
logger.Handle(error.ToString());
}
}
}
}