Build a Geometry Library with Interfaces and Classes
BehavioralModel answerLast updated
Create an abstract interface for geometric shapes and implement concrete classes for circles and rectangles with validation and immutability.
Problem
You're building a geometry library that needs to support various 2D shapes. Your task is to create a well-structured object-oriented design using an abstract interface and concrete implementations.
Build a Shape interface (or abstract base class) that defines the contract all shapes must follow, then implement two concrete shapes: Circle and Rectangle.
Interface Requirements
Your Shape interface must declare three methods:
area()— returns the shape's area as a floatperimeter()— returns the perimeter (circumference for circles) as a floatgetInfo()— returns a descriptive string about the shape
Circle Implementation
Create a Circle class that:
- Accepts a
radiusparameter in the constructor - Validates that radius is non-negative (raise an exception for invalid input)
- Implements all three
Shapemethods correctly - Uses π ≈ 3.14159... for calculations
Rectangle Implementation
Create a Rectangle class that:
- Accepts
widthandheightparameters in the constructor - Validates that both dimensions are non-negative (raise exceptions for invalid input)
- Implements all three
Shapemethods correctly
Design Constraints
- Use proper encapsulation: dimension values should be stored in private/protected attributes
- Objects must be immutable after construction — no changing dimensions later
- All validation must happen in the constructor before any state is stored
Example Interaction
shapes = [Circle(5.0), Rectangle(4.0, 6.0)]
for shape in shapes:
print(f"{shape.getInfo()}: Area={shape.area():.2f}, Perimeter={shape.perimeter():.2f}")
# Expected output:
# Circle (radius: 5.00): Area=78.54, Perimeter=31.42
# Rectangle (width: 4.00, height: 6.00): Area=24.00, Perimeter=20.00
You should be prepared to discuss your design choices and how they demonstrate OOP principles.
Hints
Hint 1
The interface should prevent instantiation of incomplete implementations — use abstract methods
Hint 2
Immutability means both preventing external modification and blocking new attributes from being added after construction
Hint 3
Validate all inputs before storing any state so invalid objects never exist
Model answer
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This problem tests understanding of four fundamental OOP principles applied together in a clean design.
Abstraction through interfaces: Define Shape as an abstract base class using Python's abc.ABC. Mark each method with @abstractmethod so Python enforces that subclasses provide implementations. Attempting to instantiate an incomplete subclass will raise TypeError immediately.
Polymorphism in action: The client code treats all shapes uniformly through the Shape interface. The loop iterates over a heterogeneous collection and calls the same methods without type-checking or branching. Each concrete class provides its own behavior.
Encapsulation of state: Store dimensions in attributes prefixed with a single underscore (e.g., _radius). Expose them through read-only properties if external code needs to inspect them. This prevents accidental modification while keeping the interface clean.
Constructor validation for invariants: Every shape must satisfy its validity constraints throughout its lifetime. Validate all inputs before assigning any state. If validation fails, raise an exception immediately so no partially-constructed object exists.
Immutability Strategy
True immutability requires blocking all mutation paths:
__slots__: Prevents adding arbitrary attributes by removing the instance__dict__- Override
__setattr__and__delattr__: Make both raiseAttributeErrorto block attribute modification and deletion - Use
object.__setattr__in__init__: This bypasses our guard exactly once during construction, allowing initialization while still blocking later changes
Without this combination, a property without a setter blocks obj.radius = 3 but doesn't prevent obj._radius = 3 or obj.new_field = value.
Mathematical Formulas
- Circle: area = πr², perimeter = 2πr
- Rectangle: area = w × h, perimeter = 2(w + h)
For the example: π × 25 ≈ 78.54 and 2π × 5 ≈ 31.42, matching expected output.
Edge Cases to Handle
Zero dimensions: The requirement says "non-negative," which includes zero. A circle with radius 0 is degenerate but valid, having area and perimeter both equal to 0. Clarify this interpretation with your interviewer — if they want strictly positive values, adjust the validation.
Negative values: Reject with ValueError since negative dimensions are nonsensical.
Non-finite numbers: float('nan') < 0 evaluates to False, so a naive check silently accepts NaN. Explicitly test for finiteness using math.isfinite().
Type safety: Reject non-numeric inputs like strings or None with TypeError. Note that bool is a subclass of int in Python, so Circle(True) would pass an isinstance(value, (int, float)) check — explicitly reject booleans.
Integer inputs: Accept integers and convert to float for consistent return types.
Complexity
Time: O(1) for construction and all methods — just arithmetic operations.
Space: O(1) per instance. The __slots__ declaration also reduces memory overhead compared to dict-backed objects, which matters if you're creating thousands of shapes.
Solution
import math
from abc import ABC, abstractmethod
from numbers import Real
def _validate(name: str, value) -> float:
"""Convert value to float after validating it's finite and non-negative."""
if isinstance(value, bool) or not isinstance(value, Real):
raise TypeError(f"{name} must be a number, got {type(value).__name__}")
value = float(value)
if not math.isfinite(value):
raise ValueError(f"{name} must be finite, got {value}")
if value < 0:
raise ValueError(f"{name} cannot be negative, got {value}")
return value
class Shape(ABC):
"""Abstract interface for 2D geometric shapes. All shapes are immutable."""
__slots__ = ()
@abstractmethod
def area(self) -> float: ...
@abstractmethod
def perimeter(self) -> float: ...
@abstractmethod
def getInfo(self) -> str: ...
def __setattr__(self, name, value):
raise AttributeError(f"Cannot modify {type(self).__name__} after creation")
def __delattr__(self, name):
raise AttributeError(f"Cannot delete attributes from {type(self).__name__}")
class Circle(Shape):
__slots__ = ("_radius",)
def __init__(self, radius: float):
object.__setattr__(self, "_radius", _validate("radius", radius))
@property
def radius(self) -> float:
return self._radius
def area(self) -> float:
return math.pi * self._radius ** 2
def perimeter(self) -> float:
return 2 * math.pi * self._radius
def getInfo(self) -> str:
return f"Circle (radius: {self._radius:.2f})"
class Rectangle(Shape):
__slots__ = ("_width", "_height")
def __init__(self, width: float, height: float):
w = _validate("width", width)
h = _validate("height", height)
object.__setattr__(self, "_width", w)
object.__setattr__(self, "_height", h)
@property
def width(self) -> float:
return self._width
@property
def height(self) -> float:
return self._height
def area(self) -> float:
return self._width * self._height
def perimeter(self) -> float:
return 2 * (self._width + self._height)
def getInfo(self) -> str:
return f"Rectangle (width: {self._width:.2f}, height: {self._height:.2f})"
Design Notes
Single underscore convention: Using _radius instead of __radius avoids name-mangling complications with __slots__. True protection comes from the __setattr__ guard, not from naming conventions.
Method naming: getInfo uses camelCase to match the specification, even though PEP 8 prefers snake_case. Acknowledge you're following the given interface.
Value semantics: Since these objects are immutable, they work well as value objects. You could add __eq__ and __hash__ methods to enable comparison and use in sets/dicts, or use @dataclass(frozen=True, slots=True) for automatic implementation.
Common Follow-up: Adding Square
A natural extension is adding a Square class. Since a square is a special rectangle, you can subclass Rectangle:
class Square(Rectangle):
__slots__ = ()
def __init__(self, side: float):
super().__init__(side, side)
@property
def side(self) -> float:
return self._width
def getInfo(self) -> str:
return f"Square (side: {self._width:.2f})"
The classic objection here is the Liskov Substitution Principle violation: a mutable Square breaks when code calls setWidth and expects height to remain independent. However, our shapes are immutable, so this failure mode cannot occur — there are no setters. Inheritance is safe in this design. Recognizing this distinction demonstrates deeper understanding. If the shapes were mutable, composition would be safer than inheritance.