Explaining the Open-Closed Principle to the Rubber Duck With a Hands-On Exercise
Understanding how the Opened-Closed principle, immutability, encapsulation, and unit tests are working with a simple, hands-on, interview problem.
1. Overview
FizzBuzz is a common interview question for junior developers. The initial requirement is to iterate through a list of numbers from 1 to 100 and print in the console:
- Fizz — if the number is divisible by 3
- Buzz — if the number is divisible by 5
- FizzBuzz — if the number is divisible by both 3 and 5
- the number itself if no criteria were met
After that, the interviewer often adds extra requirements and use-cases, to see how easy it is for you to adapt and implement the new features.
2. The Design
Even though it can be tempting to start coding using a bunch of if statements and solve the problem quickly, let’s try to take a step back and think about it first.
Firstly, we want to show that our code is testable. Asserting the console output can be…