简体   繁体   中英

Handling method signature when parameters vary according to the 1st argument

I have the below method in which the arguments to be passed to the method vary according to the value of the ENUM which is passed as the 1st argument.

 public void startReporter(ReportType reportType, long period, Class className) {
        reportHandler = new ReportHandler(metricRegistry);
        switch (reportType) {
            case CONSOLE_REPORTER:
                reportHandler.startConsoleReport(period);
                break;
            case SLF4J_REPORTER:
                reportHandler.startSLF4JReport(className,period);
                break;
            case JMX_REPORTER:
                reportHandler.startJMXReport();
        }
    }

As you can see, not all the arguments that are passed are used in all cases in the switch statement. What is the best way to address this scenario? I do not want to have 3 methods. I need to do this with only this method. It would be great if the caller of the method can have an idea of this just by looking at the signature.

the arguments to be passed to the method vary according to the value of the ENUM which is passed as the 1st argument.

I guess it is because you are mixing construction arguments with method invocation arguments.

The enum is named Report Type . A type is usually a class and the arguments you are passing to the method are the constructor arguments for a specific type. I mean you are hiding classes behind the enum.

Take a look at this restructured code and it might be clear what I mean:

public void startReporter(ReportType reportType, long period, Class className) {

  // report handler construction
  switch (reportType) {
    case CONSOLE_REPOTER:
      reportHandler = new ConsoleReportHandler(period);
      break;
    case SLF4J_REPORTER:
      reportHandler = new SLF4JReportHandler(className, period);
      break;
    case JMX_REPORTER:
      reportHandler = new JMXReportHandler();
  }

  // report handler invocation
  reportHandler.startReport();
}

Concrete types usually have different constructor arguments. So the 'problem' you describe isn't really a problem. But if you don't show me more code (especially the code that uses the method) I can't help you to re-design your code.

I guess it's the shortest way to do so:

  1. Use wrapper class in your method signature.
    void startReporter(ReportType reportType, Long period, Class className)
  2. If no parameter needed, just send null instead
    Like.
    startReporter(reportType, period, null);
    startReporter(reportType, null, null);
    startReporter(reprotType, period, className) ;

Also if var period bear un-signed value you may pass -1 instead..

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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