dimanche 21 juillet 2019

What kind of design pattern that can be solve different logic, with different amount of parameters in java?

I'm working on a code that I believe it can be a way cleaner with a design pattern.

I tried to use the factory and strategy pattern but I can't find the best one. I think the strategy is good when the function has the same output but different logic. Below is the example of a function that I want to make it cleaner.

Map<String, Object> calculateSomething(String someString, List<Integer> someListOfInteger, Map<String, Object> someMap) {
    Integer result = 0;
    Integer totalNumberCollected = 0;
    Integer iterationIndex = 0;
    for(Integer number: someListOfInteger) {

      iterationIndex++;

      // do something which will be applied for stringA or stringB

      if (someString.equals("stringA")) {
        totalNumberCollected = totalNumberCollected + 50;
        someMap.put("stringA1", "foo");
        if(iterationIndex == someListOfInteger.size()) {
          someMap.put("stringA2", number);
        }
      }
      else if (someString.equals("stringB")) {
        someMap.put("stringB1", "foo");
      }
    }
    return someMap;
  }

Could you guys help me how to make above function abstracted or transform it into a good design pattern? Thank you.

Aucun commentaire:

Enregistrer un commentaire