Member-only story

Importance of Open-Closed Principle

The O in SOLID

Skilled Coder
6 min readJan 22, 2025

Imagine you’re a software developer working on project building a feature for calculating different types of salaries. We had three main categories of employees: Full-time, Part-time, and Contractors. It seemed totally reasonable to handle this scenario in one single class that had a method like calculateSalary()—just a few conditionals, right?

The Innocent-Looking Logic

public class SalaryCalculator {

public double calculateSalary(String employeeType, double baseSalary, double hoursWorked) {
double totalSalary = 0;

if ("FULL_TIME".equalsIgnoreCase(employeeType)) {
// Full-time has some bonus
totalSalary = baseSalary + 0.2 * baseSalary;
} else if ("PART_TIME".equalsIgnoreCase(employeeType)) {
// Part-time gets half the base plus extra for hours
totalSalary = (baseSalary / 2) + (10 * hoursWorked);
} else if ("CONTRACTOR".equalsIgnoreCase(employeeType)) {
// Contractors are paid purely by the hour
totalSalary = 50 * hoursWorked;
}

return totalSalary;
}
}

At a glance, this might look acceptable, especially for a smaller codebase:

  • One class, no big fuss.
  • The method is short, easy to…

--

--

Skilled Coder
Skilled Coder

Written by Skilled Coder

Sharing content and inspiration on programming. Coding Newsletter : https://skilledcoder.substack.com

No responses yet