MediumPro challengePython

Open/Closed Principle

PythonClean CodeSOLIDOCP

Software entities should be open for extension, closed for modification. Adding a new case should not require editing existing code.

# dirty — adding a new shape requires editing solve
import math

def solve(kind, *dims):
    if kind == 'circle':
        return math.pi * dims[0] ** 2
    if kind == 'rect':
        return dims[0] * dims[1]
    if kind == 'tri':
        return 0.5 * dims[0] * dims[1]
    raise ValueError('Unknown shape')

Refactor so each shape has its own area callable. Create create_circle(r), create_rect(w, h), create_triangle(b, h). Then solve(kind, *dims) just builds the right shape and calls its area — no growing if chain needed when adding new shapes.

Sample tests

Test #1Circle r=5
Input: ["circle",5]
Output: 78.53981633974483
Test #2Rect 6×4
Input: ["rect",6,4]
Output: 24
Test #3Triangle base=7 height=5
Input: ["tri",7,5]
Output: 17.5