Skip to content

Instantly share code, notes, and snippets.

@suhailgupta03
Created December 8, 2023 15:22
Show Gist options
  • Save suhailgupta03/575c68eda51d8b10622eb165b80dc3f4 to your computer and use it in GitHub Desktop.
Save suhailgupta03/575c68eda51d8b10622eb165b80dc3f4 to your computer and use it in GitHub Desktop.
/**
* Open/Closed Principle (OCP): Software entities should be open
* for extension but closed for modification.
*/
class AreaCalculator { // BAD CODE
calculate(shape) {
if (shape instanceof Square) {
return shape.width * shape.width;
}else if(shape instanceof Circle) {
return Math.PI * shape.radius * shape.radius;
}else if(shape instanceof Rectangle) {
return shape.width * shape.height;
}else if(shape instanceof Triangle) {
return shape.base * shape.height / 2;
}else if(shape instanceof Ellipse) {
return Math.PI * shape.radiusX * shape.radiusY;
}
}
}
// Good Practice
class Shape {
area() {
throw new Error('Area method should be implemented');
}
}
class Square extends Shape {
constructor(width) {
super();
this.width = width;
}
area() {
return this.width * this.width;
}
}
class Rectangle extends Shape {
constructor(width, height) {
super();
this.width = width;
this.height = height;
}
area() {
return this.width * this.height;
}
}
class Ellipse extends Shape {
constructor(radiusX, radiusY) {
super();
this.radiusX = radiusX;
this.radiusY = radiusY;
}
area() {
return Math.PI * this.radiusX * this.radiusY;
}
}
const square = new Square(4);
const rectangle = new Rectangle(4, 5);
const ellipse = new Ellipse(4, 5);
console.log(rectangle.area()); // 20
console.log(square.area()); // 16
ellipse.area(); // 62.83185307179586
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment