1

I have a usecase where a bunch of classes have a similar paradigm and need to implement a common interface. All these classes have something in common hence I decided to abstract them out in an abstract class. For instance,

class AbstractImpl<K, V> {
  protected abstract V doGet(K key);

  protected abstract void insert(K key, V value);

  public void get(K key) {
    doGet(key);
    // generic implementation for all classes
  }

  public void insert(K key, V value) {
     doInsert(key, value);
    // generic implementation
  }
}

class ConcreteImpl extends AbstractImpl {
  // custom implementation goes here
}

My question is, should I have an interface with get(K) and insert(K, V) which AbstractImpl should extend? I understand that it is good practice to have an interface to enforce a strong contract. But in a usecase such as this, is it fine to not have an interface? The only advantage of adding an interface I see in this usecase is that, tomorrow if I have another implementation which has its own doGet and doInsert implementations (which I do not foresee in the near future), it would help. Is there any other reason why I should have an interface?

coder
  • 1,901
  • 5
  • 29
  • 44
  • try to see this for better understanding about the two: http://stackoverflow.com/questions/1913098/what-is-the-difference-between-an-interface-and-abstract-class – msagala25 Nov 21 '16 at 02:25
  • I guess you can always refactor in the future, in case you're not using it now. It also depends how the class is used - if it is part of a public interface of your library (or should we say module now?) then I'd use an interface in addition to that abstract class. You don't want to change external components if you ever decide to refactor. – Maarten Bodewes Nov 21 '16 at 02:28
  • It is just a small module which is not being used by anyone else as of now. – coder Nov 21 '16 at 02:31

0 Answers0