Give examples of the following code smells: Feature envy Dead code Duplicate code Shotgun surgery

Give examples of the following code smells:

  1. Feature envy
  2. Dead code
  3. Duplicate code
  4. Shotgun surgery

From the DPDC Assistant Manager (ICT) June 2025 – Written (BUET) exam, question 8 of 8.

Answers (1)

1. Feature Envy

A method uses another class's data more than its own.

class Invoice {
    double calculateTotal(Customer c) {
        return c.getOrders() * c.getPrice() - c.getDiscount();  // uses only Customer's data
    }
}

Fix: Move the method into Customer.

2. Dead Code

Code that is never executed or used.

int calculate(int x) {
    int unused = x * 10;        // never used
    return x + 5;
    System.out.println("Done"); // unreachable
}

void oldDiscount() { ... }      // never called anywhere

Fix: Delete it.

3. Duplicate Code

The same logic repeated in multiple places.

double studentFee(double fee) {
    return fee - fee * 0.10 + 50;
}
double staffFee(double fee) {
    return fee - fee * 0.10 + 50;  // same logic
}

Fix: Extract one shared method, e.g. applyDiscount(fee).

4. Shotgun Surgery

One small change forces edits in many different classes.

class Order    { double tax = price * 0.15; }
class Invoice  { double tax = amount * 0.15; }
class Report   { double tax = total * 0.15; }
class Cart     { double tax = sum * 0.15; }

If the tax rate changes from 15% to 10%, you must edit all four classes.

Fix: Keep the rate in one place, e.g. a TaxCalculator class.

— rhs

More from this paper