简体   繁体   English

是重载方法更好,还是使用可变参数将 0 到 1 变量传递? 爪哇

[英]Is it better to overload the method, or use varargs to pass 0 to 1 variables? Java

I'm a QA Tester.我是 QA 测试员。 My background is not the best in understanding some best practices in Java.我的背景不是最好的理解 Java 中的一些最佳实践。

Here is the scenario.这是场景。 I have one method that is used by multiple Tests.我有一种被多个测试使用的方法。 I realized that I need to put in a parameter for only very few tests into the method.我意识到我只需要在方法中放入一个参数来进行很少的测试。

public static void verifyActivity() {
        CustomViewMatchers.waitForElementToBeEnabled(withId(R.id.(...)), 5);
}

I put in a solution for this as a varargs, at the moment into the framework.我为此提出了一个解决方案作为可变参数,目前进入框架。

public static void verifyActivity(boolean... buttonDisplay) {
     if (buttonDisplay == null)
        CustomViewMatchers.waitForElementToBeEnabled(withId(R.id.(...)), 5);
}

Which solution is best practice?哪种解决方案是最佳实践? Should I overload the method, or continue to use varargs.我应该重载该方法,还是继续使用可变参数。

Unless you're developing a library there is no point in having methods for potential future use.除非你正在开发一个库,否则有可能在未来使用的方法是没有意义的。 If the method without parameters is all you need at the moment, the additional varargs one should be removed.如果您目前只需要不带参数的方法,则应删除额外的可变参数。

Obvious drawback of the varargs method is the additional null check for the parameter and of course keeping unused code around increases maintenance cost. varargs 方法的明显缺点是对参数进行了额外的空检查,当然保留未使用的代码会增加维护成本。 So if there's a chance to get rid of one of the methods it should be used.所以如果有机会摆脱它应该使用的方法之一。

As the Oracle docs point out:正如Oracle 文档指出的那样:

As an API designer, you should use them sparingly, only when the benefit is truly compelling.作为 API 设计人员,您应该谨慎使用它们,只有在好处确实令人信服时。 Generally speaking, you should not overload a varargs method, or it will be difficult for programmers to figure out which overloading gets called.一般来说,你不应该重载 varargs 方法,否则程序员很难弄清楚调用的是哪个重载。

Using varargs you can use the method with more than one parameter so i suggest to use overload.使用可变参数,您可以使用具有多个参数的方法,因此我建议使用重载。 So something like this:所以像这样:

public static void verifyActivity() {
        verifyActivity(false);
}

public static void verifyActivity(boolean buttonDisplay) {
        if(buttonDisplay){
            CustomViewMatchers.waitForElementToBeEnabled(withId(R.id.(...)), 5);
        }
// do something
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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