Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice to translate hard coded strings

Tags:

java

hardcoded

I have a finite set of strings for a product name. I also have a web service which sends one of these product names. However I need to send the product name in another format.

So I need a formatter/mapper somewhere before I send the message.

I COULD just make some hardcoded mapper class which takes in an argument and returns a hardcoded string like this:

String mapper(String productName) {
    switch (productName) {
    case "product1":
        return "prod1";
    case "product2":
        return "prod2"
}

However, I dont really like this approach, but I have a hard time trying to think up a better solution. Anyone have a better solution for this problem?

I'm considering storing the mapping in the database and then create a DAO for this mapping which instead of using a switch it uses the argument as key and then queries the database which returns the alternative product name, but I'm not sure if its really a better solution.

any thoughts?

* EDIT *

Forgot to mention this:

The original product names are currently stored in the database. I will need to translate these names without modifying the current code/table setup, i.e. I cannot edit the table and current classes, but I can create new tables/classes if needed.

like image 496
Linora Avatar asked Feb 15 '26 19:02

Linora


2 Answers

How about using properties file having content like

product1=prod1 
product2=prod2

and your method..

{
   //initializer
   Properties props = new Properties();
   props.load(...);
}

String mapper(String productName) {
   props.getProperty(productName);
}
like image 174
sanbhat Avatar answered Feb 18 '26 09:02

sanbhat


Using the database is a flexible approach, giving you the opportunity to adapt the mapping at any time, without restarting anything. However, performance may be of concern in that case. If so, build a cache of the complete mapping table and set up a regular refreshing schedule for it.

like image 42
Marko Topolnik Avatar answered Feb 18 '26 09:02

Marko Topolnik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!