Created
December 8, 2023 15:22
-
-
Save suhailgupta03/575c68eda51d8b10622eb165b80dc3f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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