Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Good practice for method in java

Tags:

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
  • 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?

like image 217
user1851366 Avatar asked Jul 31 '26 14:07

user1851366


1 Answers

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.

like image 150
jahroy Avatar answered Aug 03 '26 02:08

jahroy



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!