-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathOcp.cs
57 lines (52 loc) · 1.27 KB
/
Ocp.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
namespace Solid.OpenClosed
{
class Ocp : IPrinciple
{
public string Principle()
{
return "Open for Extension, Closed for Modification";
}
}
// Violating the Open Closed Principle
// This is bad, because at the moment, there are 2 types
// of customer, if we want to add another customer type
// we have to add a `if else` below. So Modifying the existing code
internal class Customer
{
public int Type;
public virtual void Add(Database db)
{
if (Type == 0)
{
db.Add();
}
else
{
db.AddExistingCustomer();
}
}
}
// This is better, because we structure the code so its
// easier to extend and hard to modify
internal class CustomerBetter
{
public virtual void Add(Database db)
{
db.Add();
}
}
internal class ExistingCustomer : CustomerBetter
{
public override void Add(Database db)
{
db.AddExistingCustomer();
}
}
internal class AnotherCustomer : CustomerBetter
{
public override void Add(Database db)
{
db.AnotherExtension();
}
}
}