简体   繁体   English

java中方法的好习惯

[英]Good practice for method in java

I have a method that read from database and get some string there. 我有一个从数据库读取并在那里获取一些字符串的方法。 According what I get I will override that string for another that I already know. 根据我得到的,我将覆盖我已经知道的另一个字符串。 For example: 例如:

  • strstring strstring
  • binbinary binbinary
  • and so on.. 等等..

My question is, what is the best practice for doing this? 我的问题是,这样做的最佳做法是什么? Of course I already thought about if's... 当然我已经考虑过如果......

if (str.equals("str"))
    str = "string";

A file that have this things pre-defined, a multi-dimensional array, etc.. But this all seems a quite newbie, so what do you recommend? 有预先定义过这个东西的文件,一个多维数组等等。但是这一切似乎都是一个相当新手,所以你推荐什么? What is the best way? 什么是最好的方法?

Use a Map: 使用地图:

// create a map that maps abbreviated strings to their replacement text
Map<String, String> abbreviationMap = new HashMap<String, String>();

// populate the map with some values
abbreviationMap.put("str", "string");
abbreviationMap.put("bin", "binary");
abbreviationMap.put("txt", "text");

// get a string from the database and replace it with the value from the map
String fromDB = // get string from database
String fullText = abbreviationMap.get(fromDB);

You can read more about Maps here . 您可以在此处详细了解地图

You could use a map, for example: 您可以使用地图,例如:

Map<String, String> map = new HashMap<String, String>();
map.put("str", "string");
map.put("bin", "binary");

// ...

String input = ...;
String output = map.get(input); // this could be null, if it doesn't exist in the map

Map is a good option as people have suggested. 人们建议,地图是一个不错的选择。 The other option which I normally consider in this scenario is Enum. 我通常在这种情况下考虑的另一个选项是Enum。 It gives you an additional capability of adding behavior for a combination. 它为您提供了为组合添加行为的附加功能。

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

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