0

I have a use case to store given object as JSON in local file system and my current implementation looks like below. Let's say I want to store the same object in different format in some remote location or database in the future. It require modifications in the constructor and implementation(addConfig) in ConfigStore. But, parameters of addConfig will remain same which means it will require changes only in the places where we construct the ConfigStore object.

Here, I am programming to an implementation. Though I introduce interface and modify my ConfigStore class to implement it, I still need to update all places which create instance of ConfigStore when I move to different format or data store later. So, does it really make sense to use interface for this particular use case? If yes, what are the advantages?

I know the concept of interface and I have been using it widely. But, I am trying to understand if "Program to interfaces but not implementations" is really applicable in this use case. I see many of my team mates are using interface just for the similar kind of purpose (i.e) what if we move to different store later and so, I want to get some thoughts here.

ConfigStore {
   @Autowired private final String mPathRoot;
   @Autowired private final ObjectMapper mObjectMapper;

   public void addConfig(Config config, String countryCode) {
      // Code goes here
   }
}
explorer
  • 382
  • 1
  • 13
  • Does this answer your question? [What does it mean to "program to an interface"?](https://stackoverflow.com/questions/383947/what-does-it-mean-to-program-to-an-interface) – Brian Tompsett - 汤莱恩 Jun 07 '20 at 20:39
  • @BrianTompsett-汤莱恩 The post you have shared is about understanding the program to an interface concept which I am totally aware of. But, I am trying to understand if it really makes sense to introduce interface in my case. – explorer Jun 08 '20 at 05:36

1 Answers1

0

In my opinion, coding to an interface principal should always be adopted. If you find yourself with a design in which you need to update all places that uses "ConfigStore" for new format than you need to take a closer look at your overall design.

I can think of two common pitfalls when adopting "program to interface":

  1. Creation of specific object
  2. Need for different parameters or sequence for different implementation of the interface.

Regarding the latter, it is usually solvable by rethinking your abstractions. There is no ready answer for that.

However, regarding the first pitfall, the best way to solve this is by using "dependency injection" and one of the "Factory" patterns to "hide away the mess". This way only relevant factory code will need to be updated for new "formats".

Hope this helps.

Yitshak Yarom
  • 84
  • 1
  • 4