【问题标题】:Groovy best/recommended approach to ensure correct argument type确保正确参数类型的 Groovy 最佳/推荐方法
【发布时间】:2016-01-31 19:31:55
【问题描述】:

我正在尝试以最好的“Groovy 方式”做事。 检查参数类型的最佳方法是什么(关于性能和“Groovy-way”)?我想到了 2 个实现:

def deploy(json) {
    if (!(json instanceof String) && (json instanceof File)) {
        json = json.text
    } else {
        throw new IllegalArgumentException('argument type mismatch – \'json\' should be String or File')
    }
    // TODO
}

def deploy(File json) {
    deploy(json.text)
}

def deploy(String json) {
    // TODO
}

谢谢:)

【问题讨论】:

  • 第二个。如果您的方法必须采用类型,请声明该类型。如果它返回一个类型,也要声明它

标签: java groovy method-signature


【解决方案1】:

您的问题没有什么特别之处,更多的是关于编译/运行时失败。

在第一个sn-p中json变量有Object类型,允许传入所有东西。如果你错误地传入JSON对象或Map,它将在运行时失败。

在第二个 sn-p json 被限制为 FileString。我更喜欢它。

【讨论】:

  • 我也更喜欢第二个选项——更接近Java,我更喜欢。在这种情况下,使用 Java 可能比使用 Groovy 更好。谢谢!
【解决方案2】:

instanceof 检查应该没问题。但是我认为您的情况是错误的-您似乎想这样做:

if (json instanceof File) {
    json = json.text
} else if(!(json instanceof String)) {
    throw new IllegalArgumentException('argument type mismatch – \'json\' should be String or File')
}

你也可以这样写:

if (json.class in [String.class, File.class]) {

您的第二种方法看起来更简单,只有两种方法可以通过它们的签名清楚地显示意图。

【讨论】:

  • 谢谢你的回答 :) 我认为我的逻辑是正确的,因为我期待一个字符串,所以,如果json 是一个,那么类型是正确的。除此之外,感谢.class in [...]
  • @Matheus 如果jsonString,则该条件将导致IllegalArgumentException
猜你喜欢
  • 1970-01-01
  • 2011-10-16
  • 2017-09-21
  • 2019-03-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-17
相关资源
最近更新 更多