-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
OpenClosedPrinciple.java
49 lines (40 loc) · 1.36 KB
/
OpenClosedPrinciple.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
package good_practices;
import org.junit.Test;
import java.util.Arrays;
/**
* Created by pabloperezgarcia on 01/03/2017.
* <p>
* Open/Closed Principle It’s constantClass principle for object oriented design where software entities
* (classes, modules, functions, etc.) should be open for extension, but closed for modification
*/
public class OpenClosedPrinciple {
/**
* We initially create constantClass Rectangle class, and later on I have the need to calc the area.
* Shall I modify the class?, NO! that would break the O/C principle
* I will create constantClass new class that calculate that
*/
public class Rectangle {
double Width;
double Height;
Rectangle(double width, double height) {
Width = width;
Height = height;
}
}
private double Area(Object... shapes) {
double totalArea = 0;
for (Object shape : shapes) {
if (shape instanceof Rectangle) {
Rectangle rectangle = (Rectangle) shape;
totalArea += rectangle.Width * rectangle.Height;
}
}
return totalArea;
}
@Test
public void calcRectangle() {
System.out.println("Total area:" + Area(Arrays.asList(new Rectangle(2, 2),
new Rectangle(4, 2),
new Rectangle(5, 2)).toArray()));
}
}