简体   繁体   English

翻译硬编码字符串的最佳做法

[英]Best practice to translate hard coded strings

I have a finite set of strings for a product name. 我有一组有限的产品名称字符串。 I also have a web service which sends one of these product names. 我还有一个Web服务,它发送这些产品名称之一。 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: 我可以制作一些硬编码的mapper类,它接受一个参数并返回一个硬编码的字符串,如下所示:

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. 我正在考虑将映射存储在数据库中,然后为这个映射创建一个DAO,而不是使用一个开关,它使用参数作为键,然后查询返回替代产品名称的数据库,但我不确定它是否真的是更好的解决方案

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, ie I cannot edit the table and current classes, but I can create new tables/classes if needed. 我将需要翻译这些名称而不修改当前的代码/表设置,即我不能编辑表和当前类,但我可以根据需要创建新的表/类。

How about using properties file having content like 如何使用具有类似内容的properties文件

product1=prod1 
product2=prod2

and your method.. 和你的方法..

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

String mapper(String productName) {
   props.getProperty(productName);
}

Use an enumeration (or set of integers) as ID for product 1, 2 etc. 使用枚举(或整数集)作为产品1,2等的ID。

Then use a dictionary/map/array/whatever or a get function to get the name (either "product1" or "product2"). 然后使用dictionary / map / array / whatever或get函数来获取名称(“product1”或“product2”)。 Do not use strings when you want to USE these types, becasue they tend to occur more than one time in your code and if you forget to change it at one location you get inconsistencies. 当您想要使用这些类型时不要使用字符串,因为它们往往会在代码中出现多次,如果您忘记在某个位置更改它,则会出现不一致。

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. 如果是这样,请构建完整映射表的缓存并为其设置定期刷新计划。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM