1

Say, I have a String values of "CHAR","VARCHAR", "NUMBER" and so on from one side and JDBCType.CHAR, JDBCType.VARCHAR, JDBCType.INTEGER from other side.

I can implement the conversion as simple as :

public static JDBCType convertFromStringToJDBCType(String datatype) {
switch(datatype) {
  case "VARCHAR":
    result = JDBCType.VARCHAR;
    break;
  case "NUMBER":
    result = JDBCType.INTEGER;
    break;
...
}

The downside of this approach is that I have to build the exact opposite of this function to convert values back.

What is the optimal way to implement such a conversion?

Michael
  • 2,835
  • 2
  • 9
  • 15

3 Answers3

3

There is nothing wrong with a "central" switch statement, as long as you don't start to "copy" it in different places. A single switch is OK, typically "trouble" starts when the "same" switch code exists in more than one place.

If at all, you could consider to put this mapping information into a distinct map typesByString.put("VARCHAR", JDBCType.VARCHAR) and so on.

If you want to in "both" directions, you want to look into (surprise) bidi maps!

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • When using approach of distinct map, what is the best way to implement reverse-conversion (from value to key - > from JDBCType.VARCHAR to "VARCHAR")? – Michael Nov 10 '18 at 20:03
  • @Michael See the update I just made. And just for the record: dont forget about accept an answer at some point ;-) – GhostCat Nov 10 '18 at 20:08
1

You can also use the built-in valueOf(String) method from Enum. Smth like

result = JDBCType.valueOf(datatype);

dehasi
  • 2,644
  • 1
  • 19
  • 31
0

You can create Map<String, JDBCType> and use it to convert key to value and value to key. If value to key you finds slow, then you can create another, opposite, Map<JDBCType, String>.

Oleg Cherednik
  • 17,377
  • 4
  • 21
  • 35