3

A Java project I've been working on integrates with several RDBMSs. The most obvious way for us to reduce the code duplication between the way we handle them is to make a type hierarchy like:

               ThirdPartySoftware (superclass)
                      /|\
                     / | \
                 TPS1  2  3

However, this approach has ended up with implementations for TPS1, TPS2, and TPS3 being very similar (but not quite!). It's difficult to pull all the functionality into the superclass without the superclass essentially being aware of every place that something could be different, defeating the encapsulation subclassing is meant to buy us.

One method we've considered is representing the DBs by features that they share, such as "supports feature X" and "can't do feature Y", however it's not altogether clear that the code would end up being more maintainable that way because:

  1. Many of the quirks only apply to one DB.
  2. We can't think of enough shared/comparable (basically, abstract-able) features to make this worthwhile.

Does anyone have other suggestions of ways we could reduce the code duplication between the subclasses, perhaps using a design pattern?

Dan
  • 7,155
  • 2
  • 29
  • 54
  • If there's no code that can be abstracted out, then I'd say you'd just need to write it out. For features that can be abstracted out, maybe [mixins](https://en.wikipedia.org/wiki/Mixin) would work. – Fred Foo Apr 04 '13 at 15:51
  • Scala does this well with traits. Around stackoverflow a few people propose mixins/traits implementations in Java such as [here](http://stackoverflow.com/questions/7152027/ways-to-achieve-effective-java-traits) or [here](http://stackoverflow.com/questions/587458/implement-mixin-in-java) – Bruno Grieder Apr 04 '13 at 16:24
  • Just a thought - why not use hibernate or other ORM Framework. – Atul Apr 05 '13 at 10:12
  • I worded the question a little vaguely, but we're performing administration actions on the databases and the underlying database files, not storing objects in them, so sadly an ORM would not help us in this case. – Dan Apr 05 '13 at 17:32

2 Answers2

5

http://en.wikipedia.org/wiki/Bridge_pattern

looks just for your case but anyway it will be your job to find out what is the API.

Perhaps, org.hibernate.dialect.Dialect will give you some new ideas.

Vitaly
  • 2,760
  • 2
  • 19
  • 26
0

I am not a java guy, but in addition to the superclass / abstract class you could use interfaces and dependency injection along with the repository pattern. These patterns are not exclusive, I frequently have interface implementations that are subclasses of a master class such as

SqlDataAccess : BaseDataAccess, IDataAccess and TPSDataAccess : SqlDataAccess, ITPSDataAccess

Rob Allen
  • 2,871
  • 2
  • 30
  • 48