Interface means strategy


If you see an interface in the source code:

interface Discount {
   calculate (double price);
}

what do you expect?

I expect many (at least two) implementations:

class IndividualDiscount implements Discount {
   calculate (double price) {
      return price * 0.9;
   }
}
class CompanyDiscount implements Discount {
   calculate (double price) {
      return price * 0.7;
   }
}

which we choose depending on certain conditions – such a mechanism is called a strategy pattern.

Why am I writing about this? Because I have seen in many projects such code:

interface Car {
   drive();
}
class CarImpl implements Car { //just one implementation of Car interface
   drive() {}
}

Yes, interface and only one implementation!
Why? I don’t know. Maybe the company pays for the number of classes or lines of code, or maybe someone thought it looked more professional 🙂

Of course, we can use interfaces to hide information/implementation and decouple implementation (as in ports&adapters), but I’m talking about a simple case: one interface and one implementation with no purpose.

You may think, does it matter? Yes, it does.

Aside from the fact that you will probably call the implementation as xxxImpl and it looks weird and there is more code to maintain, one thing is particularly important

Why creating an interface for just one implementation is a bad thing?

  • Expressing wrong assumptions!

When you see an interface, you first, expect multiple implementations and strategy pattern. You start looking for many implementations, but you can’t find them. This is frustrating. You start thinking about why someone made the effort to create more code. Your brain generates ideas and eventually, you give up, but you have wasted a lot of energy on such silly things!

Summary

Don’t create an interface just for one implementation! if you don’t have any special purpose now.


Leave a Reply

Your email address will not be published. Required fields are marked *