Mark As Completed Discussion

Open-Closed Principle (OCP)

The Open-Closed Principle (OCP) is one of the five object-oriented design principles that form the SOLID principles. It states that software entities (classes, modules, functions, etc.) should be open for extension but closed for modification.

This means that once a software entity is implemented and tested, it should not be modified to add new functionality. Instead, new functionality should be added by extending or subclassing the existing entity.

The OCP promotes extensibility and avoids the need to modify existing code, reducing the risk of introducing bugs. It encourages the use of abstraction and inheritance to allow for easy addition of new features.

For example, let's consider a Shape class that has a method to calculate the area:

TEXT/X-JAVA
1abstract class Shape {
2  abstract double calculateArea();
3}
4
5class Rectangle extends Shape {
6  private double width;
7  private double height;
8
9  public Rectangle(double width, double height) {
10    this.width = width;
11    this.height = height;
12  }
13
14  @Override
15  double calculateArea() {
16    return width * height;
17  }
18}
19
20class Circle extends Shape {
21  private double radius;
22
23  public Circle(double radius) {
24    this.radius = radius;
25  }
26
27  @Override
28  double calculateArea() {
29    return Math.PI * radius * radius;
30  }
31}
32
33public class Main {
34  public static void main(String[] args) {
35    // Code to calculate the area of different shapes
36    Shape rectangle = new Rectangle(4, 5);
37    Shape circle = new Circle(3);
38
39    System.out.println("Area of rectangle: " + rectangle.calculateArea());
40    System.out.println("Area of circle: " + circle.calculateArea());
41  }
42}

In this example, the Shape class is open for extension as new shapes can be added by creating new subclasses such as Rectangle and Circle. The existing code does not need to be modified to accommodate new shapes.

By adhering to the Open-Closed Principle, we can design code that is easily maintainable, reusable, and scalable.

JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment