Refactor Switch Statements with Polymorphism (Best OOP Approach!)

Sanjay Singh
2 min readFeb 4, 2025

--

Why Use Polymorphism Over Switch-Case?

  1. Extensible & Open-Closed Principle (OCP) — New behavior can be added without modifying existing code.
  2. Encapsulation — Each behavior is self-contained within its class.
  3. No Risk of break Omissions – Eliminates common switch-case pitfalls.
  4. Readable & Maintainable — Code is more structured and easier to test.
Refactor Switch Statements with Polymorphism (Best OOP Approach!)

Story List Categories:

  • About Me & List of Stories
  • Java — All things Java-related.
  • Java Interview Playbook: Your Go-To Reading List — For interview preparation.
  • JAVA-8 — Dedicated to Java 8 topics.
  • Spring Boot & Spring — Focused on Spring and Spring Boot.
  • Microservices Topics List — Covering various microservices to

📝 The Problem: Hardcoded Conditions for Different Employees

public class SalaryService {
public double calculateSalary(String employeeType, double baseSalary) {
switch (employeeType) {
case "FULL_TIME":
return baseSalary * 1.2;
case "PART_TIME":
return baseSalary * 1.1;
case "INTERN":
return baseSalary * 0.8;
default:
return baseSalary;
}
}
}

✔ Works, but not extensible.
❌ Violates Open/Closed Principle (OCP).

Solution: Use Polymorphism (Best Object-Oriented Approach!)

interface Employee {
double calculateSalary(double baseSalary);
}

class FullTimeEmployee implements Employee {
public double calculateSalary(double baseSalary) {
return baseSalary * 1.2;
}
}

class PartTimeEmployee implements Employee {
public double calculateSalary(double baseSalary) {
return baseSalary * 1.1;
}
}

class Intern implements Employee {
public double calculateSalary(double baseSalary) {
return baseSalary * 0.8;
}
}

public class SalaryService {
public double calculateSalary(Employee employee, double baseSalary) {
return employee.calculateSalary(baseSalary);
}
}

No Hardcoded Conditions — Each employee type has its own class.
More Maintainable — Adding new employee types doesn’t modify existing code.
OOP Best Practice — Leverages Polymorphism instead of conditionals.

🔥 Use Polymorphism to eliminate switch-case and write scalable OOP code! 🚀

Story List Categories:

  • About Me & List of Stories
  • Java — All things Java-related.
  • Java Interview Playbook: Your Go-To Reading List — For interview preparation.
  • JAVA-8 — Dedicated to Java 8 topics.
  • Spring Boot & Spring — Focused on Spring and Spring Boot.
  • Microservices Topics List — Covering various microservices to

--

--

Sanjay Singh
Sanjay Singh

Written by Sanjay Singh

Java, Spring Boot & Microservices developer Sharing knowledge, tutorials & coding tips on my Medium page. Follow me for insights & see story list section

No responses yet