0%
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
Abstract Shape
Concrete Shapes
ShapeFactory
Design Patterns
Polymorphism: The Core Pattern
Factory Method: Shape Creation
Strategy Pattern: Pluggable Comparisons
Define Class Members / Write Code
Circle
Rectangle
Triangle with Heron's Formula
ShapeCalculator
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Parallel Computation
DoubleAdder vs. Reduce
Composite Pattern for Complex Shapes
Create/Explain Your Diagrams
Future Improvements
A shape calculator sounds like a collection of geometry formulas. But a well-designed system must enforce polymorphism so that calculating total area across mixed shapes requires zero type checking, validate dimensions at construction time so invalid shapes are structurally impossible, support aggregate operations over large collections with parallel computation, and allow new shape types to be added without modifying any existing class. The design challenge is building a hierarchy where every shape is interchangeable through a single abstract interface.
Interview Dialogue
Functional Requirements
Non-Functional Requirements
Start from the goal: calculator.totalArea(shapes) where shapes is a mixed list of circles, rectangles, and triangles. Imagine a CAD application where the user draws shapes on a canvas and the toolbar shows total area and total perimeter. Every shape the user draws must be calculable by the same code path, regardless of type.
Start by scanning the requirements for nouns. "Circles with radius" gives us Circle. "Rectangles with length and width" becomes Rectangle. "Triangles with three sides" maps to Triangle. "Calculator for total area and perimeter" gives us ShapeCalculator. Not every noun becomes a class. "perimeter" is a computed value returned by a method, not its own entity, but nouns give you the starting lineup.
For this to work without type checking, every shape must have the same interface. An abstract Shape class defines getArea() and getPerimeter(). All concrete shapes extend it.
Circle has a radius. Area = pi * r^2. Perimeter = 2 * pi * r. The constructor validates that radius is positive.
Rectangle has length and width. Area = length * width. Perimeter = 2 * (length + width). The constructor validates both dimensions are positive.
Triangle has three side lengths. Area uses Heron's formula: sqrt(s * (s-a) * (s-b) * (s-c)) where s is the semi-perimeter. Perimeter = a + b + c. The constructor validates all sides are positive and the triangle inequality holds (any two sides sum to more than the third).
A ShapeCalculator operates on List<Shape>. It computes totalArea(), totalPerimeter(), largestByArea(), and sortByArea(). It never knows the concrete type of any shape.
A ShapeFactory provides creation methods: createCircle(radius), createRectangle(l, w), createTriangle(a, b, c). The factory centralizes validation and construction.
Why a separate Shape class instead of combining its responsibilities into Circle? Each class should have one reason to change. If Circle handled both its own logic and Shape logic, a change to either concern would risk breaking the other.
Inheritance: Circle, Rectangle, Triangle extend Shape
This is the core relationship. All concrete shapes inherit the abstract contract (getArea, getPerimeter) and the shared implementations (compareTo, toString). The ShapeCalculator and any other consumer code depends on Shape, not on concrete types.
Polymorphism: ShapeCalculator operates on Shape
ShapeCalculator accepts List<Shape> and calls getArea()/getPerimeter() on each element. It never knows or cares what the concrete type is. This is polymorphism in action: one interface, many implementations.
Factory: ShapeFactory creates concrete shapes
ShapeFactory provides typed creation methods. The factory is the only place where concrete types are named. After creation, all shapes are referenced as Shape. This concentrates type awareness in one place.
Why not use instanceof checks in ShapeCalculator.totalArea() instead of polymorphism? Because every new shape type would require adding another branch. Forgetting the Pentagon branch means silently skipping pentagons and producing wrong totals. Polymorphism makes this impossible since every Shape must implement getArea().
Comparator as Strategy
Shape implements Comparable<Shape> with a default comparison by area. For different sorting criteria, callers provide a Comparator<Shape>. This is the Strategy pattern: the sorting criterion is a pluggable strategy, not a hardcoded behavior.
No ownership relationship
ShapeCalculator does not own or store shapes. It accepts a list as a parameter, computes results, and returns them. This is a stateless utility: no composition, no aggregation, just a method dependency.
Three abstract methods that every shape must implement. Two concrete methods that all shapes inherit. compareTo() sorts shapes by area. toString() provides a consistent string representation.
Why abstract class instead of interface? The default compareTo() and toString() implementations are shared behavior that all shapes inherit. An interface with default methods could achieve the same, but an abstract class communicates more clearly that Shape is a base type with shared state management potential.
Why not make shape fields mutable so you can resize shapes after creation? Because shapes are used as collection elements and map keys. If you change a circle's radius after inserting it into a sorted list, the sort order is silently corrupted. Making fields final enforces immutability at the language level, preventing this entire class of bugs.
Circle, Rectangle, and Triangle each extend Shape with final fields (immutable after construction) and constructor validation. All fields are final because shape dimensions never change after creation. A circle with radius 5 stays radius 5 forever.
The factory provides static creation methods. It is the single place where concrete types are instantiated. Application code receives Shape references and never imports Circle, Rectangle, or Triangle.
The entire design is built on polymorphism. ShapeCalculator.totalArea() iterates over List<Shape> and calls getArea() on each element:
No instanceof. No casting. No type checking. Adding Pentagon requires zero changes to this method. This is the Open/Closed Principle in its purest form.
ShapeFactory centralizes construction and validation:
After creation, all three variables have the same type: Shape. The concrete type is invisible to the rest of the application.
Different sorting criteria use different Comparators:
The comparison criterion is a pluggable strategy. The data structure and sorting algorithm are unchanged.
The Shape Calculator is the purest demonstration of polymorphism in OOD. ShapeCalculator never sees, names, or checks a concrete shape type. It operates entirely on the Shape abstraction. Adding Pentagon requires zero changes to any existing class.
Code Triangle early instead of leaving it for last. Circle and Rectangle only prove straightforward formulas. Triangle proves the real design point: constructor validation protects every downstream aggregate from NaN and impossible geometry.
Circle has a single final field: radius. The constructor validates radius is positive. getArea() returns pi times radius squared. getPerimeter() returns 2 times pi times radius. The immutability is enforced at the language level through the final keyword.
Rectangle has two final fields: length and width. Both must be positive. The formulas are straightforward, but the constructor validation ensures no Rectangle can exist with zero or negative dimensions.
Triangle is the most interesting concrete shape because it requires the triangle inequality validation. Without it, Heron's formula produces NaN for physically impossible triangles, silently corrupting every downstream calculation.
ShapeCalculator is a stateless utility that operates entirely on the Shape abstraction. It never imports Circle, Rectangle, or Triangle. Every method accepts List of Shape and returns results through polymorphic dispatch.
totalAreaParallel() uses parallel streams with a reduce operation. The stream partitions the list, computes partial sums in parallel, and merges them. No shared mutable state is involved: each thread works on its partition and the reduction is associative.
Browse the complete solution code and run it. Try modifying the code to experiment with the design.
Single Responsibility Principle
Open/Closed Principle
Liskov Substitution Principle
Interface Segregation Principle
Dependency Inversion Principle
In interviews, count the unchanged files when adding Pentagon: ShapeCalculator (unchanged), Circle (unchanged), Rectangle (unchanged), Triangle (unchanged), Shape (unchanged). Five files untouched. One new file. That is OCP in action.
For large shape collections (millions of shapes in a CAD application), parallel computation significantly improves throughput. The totalAreaParallel() method uses parallelStream().mapToDouble().reduce(), which partitions the list, computes partial sums on separate threads, and merges them.
Do not parallelize totals with a shared mutable accumulator like total += shape.getArea() inside parallel work. That turns a clean numeric problem into a race condition. Parallel shape aggregation should use reduction so each thread owns a partial sum.
Why not use a shared accumulator? Here is the exact failure sequence:
The reduce approach avoids shared mutable state entirely. Each thread works on its partition. The merge is associative and commutative (Double::sum). No locks are needed.
An alternative parallel approach uses DoubleAdder:
DoubleAdder maintains per-thread cells that are summed on demand. This avoids contention on a single shared variable. However, the reduce approach is preferred because it avoids shared mutable state entirely.
A CompositeShape combines multiple shapes. Its getArea() returns the sum of its children's areas. This enables treating a group of shapes as a single Shape for uniform processing.
Junior: explain polymorphism and why ShapeCalculator does not check types.
Mid-level: compare parallel stream reduce to DoubleAdder for concurrent area computation.
Senior: discuss the Composite pattern for complex shapes and the Visitor pattern for adding operations without modifying shape classes.
Why ConcurrentHashMap instead of synchronizing a regular HashMap? A synchronized HashMap locks the entire map for every operation, serializing all threads. ConcurrentHashMap uses striped locks (one per segment), so threads operating on different segments proceed in parallel.
Below is the class diagram for the shape calculator system.
Key points to highlight in an interview:
3D Shapes
Extend the hierarchy with a Shape3D abstract class adding getVolume() and getSurfaceArea(). Sphere, Cube, and Cylinder implement it. ShapeCalculator gains corresponding 3D aggregation methods. The 2D and 3D hierarchies can coexist because Shape3D extends a common base or a separate interface.
Composite Shapes
A CompositeShape combines multiple shapes using the Composite pattern. It implements Shape, computing area as the sum of its children's areas. This allows treating groups of shapes as a single Shape for uniform processing in ShapeCalculator.
Serialization and Persistence
Save and load shape collections to/from JSON or a database. A ShapeSerializer handles conversion. Each shape type has a type discriminator field in the JSON, and the deserializer uses a factory to recreate the correct concrete type.
Visitor Pattern for Cross-Cutting Operations
If you need operations that depend on the concrete type (rendering, exporting to SVG, computing bounding boxes) without modifying shape classes, the Visitor pattern allows adding new operations without changing existing shapes. Each shape implements accept(ShapeVisitor), and new operations are new visitor implementations.
Interactive Shape Editor
A GUI application where users create, resize, and arrange shapes. The Shape hierarchy provides the model. A separate rendering layer draws shapes on a canvas. The editor uses the Observer pattern to update the display when shapes change.
Reading a solution is not the same as producing one under interview pressure. Design it on the whiteboard and get scored feedback.
0%
Requirements
Define Core Objects
Analyze Relationships
Establish Hierarchy
Abstract Shape
Concrete Shapes
ShapeFactory
Design Patterns
Polymorphism: The Core Pattern
Factory Method: Shape Creation
Strategy Pattern: Pluggable Comparisons
Define Class Members / Write Code
Circle
Rectangle
Triangle with Heron's Formula
ShapeCalculator
Run and Test
Adhere to SOLID Guidelines
Consider Scalability and Flexibility
Parallel Computation
DoubleAdder vs. Reduce
Composite Pattern for Complex Shapes
Create/Explain Your Diagrams
Future Improvements