Last active
July 8, 2023 12:33
-
-
Save hawkkiller/0fb6552c2723df3e8e335a2cd98193a0 to your computer and use it in GitHub Desktop.
Open-closed principle violation example
This file contains 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
sealed class Shape {} | |
class Circle extends Shape { | |
Circle(this.radius); | |
final double radius; | |
} | |
class Rectangle extends Shape { | |
Rectangle(this.width, this.height); | |
final double width; | |
final double height; | |
} | |
class SquareCalculator { | |
double calcSquare(Shape shape) { | |
if (shape is Circle) { | |
return 3.14 * shape.radius * shape.radius; | |
} | |
if (shape is Rectangle) { | |
return shape.width * shape.height; | |
} | |
throw 'Unrecognized Shape'; | |
} | |
} | |
void main() { | |
final calculator = SquareCalculator(); | |
final circle = Circle(25); | |
// prints 1962,5 | |
print(calculator.calcSquare(circle)); | |
final rectangle = Rectangle(10, 20); | |
/// prints 200 | |
print(calculator.calcSquare(rectangle)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment