Explaining the Open-Closed Principle to the Rubber Duck With a Hands-On Exercise

Emanuel Trandafir
Javarevisited
Published in
3 min readOct 2, 2022

--

Understanding how the Opened-Closed principle, immutability, encapsulation, and unit tests are working with a simple, hands-on, interview problem.

Photo by Brett Jordan on Unsplash

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.

Photo by Sven Mieke on Unsplash

Firstly, we want to show that our code is testable. Asserting the console output can be…

--

--

Emanuel Trandafir
Javarevisited

Hi, I'm Emanuel Trandafir, a Java developer from Romania. I have a strong passion for clean code, software design, and unit testing.