KISS in Java

The KISS principle says: write the simplest code that solves the problem without unnecessary complexity.


🚨 Without KISS (Over-Engineered Example)

public class DiscountCalculator {

    // Overcomplicated discount logic
    public double calculateDiscount(double price, String customerType) {
        if (customerType.equals("REGULAR")) {
            if (price > 100) {
                return price * 0.9;
            } else {
                return price * 0.95;
            }
        } else if (customerType.equals("VIP")) {
            if (price > 200) {
                return price * 0.8;
            } else {
                return price * 0.85;
            }
        } else {
            return price; // No discount
        }
    }

    public static void main(String[] args) {
        DiscountCalculator calc = new DiscountCalculator();
        System.out.println(calc.calculateDiscount(120, "REGULAR"));
        System.out.println(calc.calculateDiscount(250, "VIP"));
    }
}

🔴 Problem:

  • Too many nested if-else blocks.
  • Hard to read and maintain.

✅ With KISS (Simplified Version)

public class DiscountCalculator {

    public double calculateDiscount(double price, String customerType) {
        switch (customerType) {
            case "REGULAR":
                return price * (price > 100 ? 0.9 : 0.95);
            case "VIP":
                return price * (price > 200 ? 0.8 : 0.85);
            default:
                return price; // No discount
        }
    }

    public static void main(String[] args) {
        DiscountCalculator calc = new DiscountCalculator();
        System.out.println(calc.calculateDiscount(120, "REGULAR")); // 108.0
        System.out.println(calc.calculateDiscount(250, "VIP"));     // 200.0
    }
}

✅ Benefits of KISS here:

  • Readable: Logic is short and clear.
  • Maintainable: Easy to extend (add new customer type).
  • Efficient: No unnecessary complexity.

🔑 KISS in Practice

  • Prefer simple conditions over deeply nested ones.
  • Don’t abstract too early — keep things straightforward.
  • Code for clarity first, optimize later if needed.

Leave a Reply