Skip to content

Instantly share code, notes, and snippets.

@hawkkiller
Last active July 8, 2023 12:33
Show Gist options
  • Save hawkkiller/0fb6552c2723df3e8e335a2cd98193a0 to your computer and use it in GitHub Desktop.
Save hawkkiller/0fb6552c2723df3e8e335a2cd98193a0 to your computer and use it in GitHub Desktop.
Open-closed principle violation example
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