【问题标题】:Handling method signature when parameters vary according to the 1st argument当参数根据第一个参数而变化时处理方法签名
【发布时间】:2016-12-21 07:08:49
【问题描述】:

我有以下方法,其中要传递给方法的参数根据作为第一个参数传递的 ENUM 的值而变化。

 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();
        }
    }

如您所见,并非所有传递的参数都在 switch 语句中的所有情况下使用。解决这种情况的最佳方法是什么?我不想有 3 种方法。我只需要用这种方法来做到这一点。如果方法的调用者可以通过查看签名来了解这一点,那就太好了。

【问题讨论】:

  • 创建重载,在调用 main 方法时为可选参数传递 null
  • 创建重载等于有 3 种不同的方法来调用记者,而不需要枚举,不是吗?
  • 没有。您的逻辑仍将封装在单个方法中(就像现在一样),重载将只是参数组合的包装器。
  • 当有人使用 reportType = JMX_REPORTER 调用“startReporter”时,方法调用会是什么样子。是 startReporter(ReportType.JMX_REPORTER, null, null) 吗??
  • 有些东西闻起来不太对劲。 reportHandler 在您调用 start....() 方法后立即超出范围。 ReportHandler 对象真的是短暂的并且不需要吗?或者,它有一些静态副作用吗?

标签: java oop design-patterns methods signature


【解决方案1】:

我想这是最短的方法:

  1. 在方法签名中使用包装类。
    void startReporter(ReportType reportType, Long period, Class className)
  2. 如果不需要参数,只需发送null
    喜欢。
    startReporter(reportType, period, null);
    startReporter(reportType, null, null);
    startReporter(reprotType, period, className);

另外,如果 var period 带有未签名的值,您可以改为传递 -1..

【讨论】:

    【解决方案2】:

    要传递给方法的参数根据作为第一个参数传递的 ENUM 的值而变化。

    我猜这是因为您将构造参数与方法调用参数混合在一起。

    枚举名为ReportTypetype 通常是一个类,传递给方法的参数是特定类型的构造函数参数。我的意思是你在枚举后面隐藏了类。

    看看这个重组后的代码,我的意思可能就很清楚了:

    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();
    }
    

    具体类型通常有不同的构造函数参数。因此,您描述的“问题”并不是真正的问题。但是如果你不向我展示更多代码(尤其是使用该方法的代码),我无法帮助你重新设计你的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-05-02
      • 2020-09-24
      • 2012-03-11
      • 1970-01-01
      • 2019-03-10
      • 1970-01-01
      • 2018-06-18
      相关资源
      最近更新 更多