Search code examples
javafunctionhashmapoverloading

Overload method with different HashMap parameters


I'm making this method with multiple parameters: createExportJob (String testId, Long otherId ) to reduce duplicate code. this example of the method should be the minimum amount of parameters the method should use.

private void createExportJob (String testId, Long otherId )  {
        String testname = getTestName(testId);

        Configuration config = itsExportService.getConfiguration();
        Map<String, String> params = new HashMap<>();
        params.put("EXAMPLE", config.getExample();
        params.put("EXAMPLENAME", config.getExampleName();
        params.put("TESTNAME", testName);
        ExportJob queuedJob = ExportQueue.addJob(params, testId, otherId);

    }

In some cases i want to include more params.put to the HashMap in the method, like this:

  params.put("THEYESNO", theYesNo ? "YES" : "NO"); 

Or

  params.put("COORDINATES", String.valueOf(minX)+","+String.valueOf(minY)+"
        ',"+String.valueOf(maxX)+","+String.valueOf(maxY));

How do I overload this method with more input parameters? Or is there any better solution to solve this case than overloading?


Solution

  • I would suggest using a Builder.

    class ExportJobConfigBuilder {
     Map<String, String> params = new HashMap<>();
     public Map<String, String> build() {
      return params;
     }
     // fill basic data in constructor
     public ExportJobConfigBuilder (String name, Configuration config) {
      params.put("TESTNAME", name);
      params.put("EXAMPLE", config.getExample();
      params.put("EXAMPLENAME", config.getExampleName();
      return this;
     }
     public ExportJobConfigBuilder withCoords(int minX, int minY, int maxX, int maxY) {
      params.put("COORDINATES", String.format("%d,%d,%d,%d", minX, minY, maxX, maxY);
      return this;
     }
     public ExportJobConfigBuilder withYesNo(boolean yesNo) {
      params.put("THEYESNO", theYesNo ? "YES" : "NO");
      return this;
     }
    }
    

    Now you have ultimate flexibility in choosing what information you add without adding separate methods for each combination. You'd call it with

    ExportJobConfigBuilder builder = 
      new ExportJobConfigBuilder(getTestname(testId), itsExportService.getConfiguration());
    builder.withCoords(minx, miny, maxx, maxy); // or not
    builder.withYesNo(yesNo); // or not
    Map<String, String> params = builder.build();
    
    ExportJob job = ExportQueue.addJob(params, testId, otherId);
    

    If you need to add additional parameters on the way, you will only need to add one method to the builder, and you can leave existing code untouched.