April 2018
Beginner
536 pages
13h 21m
English
The open/closed principle (OCP) recommends that we design our classes and methods in a way that enables us to extend their behavior (open for extension) in the future without modifying their current behavior (closed for modification).
The following code snippet is not great because it does not adhere to the open/closed principle:
class Rectangle {
public width!: number;
public height!: number;
}
class AreaCalculator {
public area(shapes: Rectangle[] ) {
return shapes.reduce(
(p, c) => {
return p + (c.height * c.width);
},
0
);
}
}
The preceding code does not adhere to the open/closed principle because if we need to extend our program to also support circles, we will need to modify the existing AreaCalculator ...