Reputation: 8923
I have a very simple application which needs a data source. At present it is a flat file but later on it will change to a database. I need your opinion on using inheritance or interfaces here. Which one would be better and why? My opinion is using interfaces because it would be flexible but then i could make data source as an abstract class too.
Upvotes: 5
Views: 232
Reputation: 42020
You can use the DAO design pattern and Factory. You can find an example in Advanced DAO programming and more information in Core J2EE Patterns - Data Access Object.
Upvotes: 0
Reputation: 1303
As you mentioned in your post, it would be best to create an interface which defines the operations which can be done on your data source. For each single data source you can create a class which implements that interface.
To operate on a flat file you could implement the class FileDataWrapper implements DataWrapper
, where the class FileDataWrapper implements the operations that can be performed on the data source. Later, when you change to a database, just implement the class DatabaseDataWrapper implements DataWrapper
.
Upvotes: 0
Reputation: 892
I would go with an abstract class. Going about a pure-object oriented approach, the class would be very small, only the necessities, and then have the child classes contain all parameters and values for the objects.
An example of what would be in the abstract class to get you ready for the database you plan is an int
for the unique id.
Upvotes: 0
Reputation: 5205
In this case, it would be more convenient to use an interface.
By abstracting out the implementation details, you can provide a common interface that both the flat-file and database backed can use. When it comes time to change, only the code of implementing this interface will change and not any code using them.
Upvotes: 0
Reputation: 56390
You use an interface when only the methods and types for accessing the data will remain the same. You use inheritance when there will be common code/functionality between things that needs to be shared as well.
In this case, it would seem an interface would suffice and utilizing an abstract class with no common code would be a waste. One often forgotten benefit of using interfaces is that you can implement multiple interfaces at once whereas you can only inherit from one parent class.
Upvotes: 2
Reputation: 96385
You would use an abstract class where there is common functionality that all the implementations need access to. Here the database and file implementations are so different they will have nothing in common, so I'd go with interfaces.
Upvotes: 8