lundi 7 décembre 2020

Java - Replacing if/else with HashMap - Optimized Approach

I have a class with almost 500 if/else, and in each if statement, I am checking contains some string if it is positive then I will set some values in a model object. Now I am doing the activity of cleaning the entire class or redesign it. So I thought to have a static Hash Map with condition string and a model object with the values set in it. The thing is the actual raw log comes from external devices so once the log comes in, i should iterate the whole map and take the values set model object, So Is there a way to use any algorithmic approach to reorder the Map by keeping the matched index at the first position, So that the next time it will be do it in a fraction of seconds. Is it the correct way to design or any other better approach for parsing data in real time streaming in java without huge number of if/else or regexes?

For Example:

Existing Code :

    public class WindowsParser{
      
    public ModelDo parse(String rawLog){
         ModelDo modelDo = new ModelDo();
         if(rawLog.contains("Source Address"){
             modelDo.setActivity("Source Enabled");
             modelDo.setType("Management events");
             modelDo.setSign("An Operation Was performed On An Object");
             return modelDo;
         } else if(rawLog.contains("Destination Address")){
             modelDo.setActivity("Destin Enabled");
             modelDo.setType("Management events");
             modelDo.setSign("An Operation Was performed On An Object");
             return modelDo;
         }
//Many if else for around 2000 lines
    }
    }

New Code to develop:

public class WindowsParser{

private static final Map<String, ModelDo> modelMap = new HashMap<String, ModelDo>();
static{
fillModelMap();
}
private static void fillModelMap(){
//This will be filled taking data from csv file.
modelMap.put("Source Address", new ModelDo("Source Enabled","Management events","An Operation Was performed On An Object");
modelMap.put("Destination Address", new ModelDo("Destin Enabled","Management events","An Operation Was performed On An Object");
}
public ModelDo parse(String rawLog){
for (Map.Entry<String, String> entry : modelMap.entrySet()) {
if(rawLog.contains(entry.getKey())
return entry.getValue();
}

}

Thanks in Advance

Aucun commentaire:

Enregistrer un commentaire