简体   繁体   English

返回值的Java错误/异常处理

[英]Java Error/Exception handling with returning value

So my friend and I are programming Blackjack in Java, and we wanted to test our input fields for the correct input(eg only number input). 因此,我和我的朋友正在用Java编程二十一点,我们希望测试输入字段的正确输入(例如,仅数字输入)。 So we sat at his PC and he wrote this solution: 因此,我们坐在他的PC上,他编写了以下解决方案:

    public static boolean testeTextFieldInt(JTextField textField,  int geld) {
    if (!textField.getText().isEmpty()) {
        try {
            if(Integer.parseInt(textField.getText())>0 && Integer.parseInt(textField.getText())<geld ) {
            return true;    
            }
        } catch (NumberFormatException e) {
            return false;
        }
    }
    return false;
}

now I disagree with this solution, because your code shouldn't depend on an error, or am I getting this wrong? 现在,我不同意这种解决方案,因为您的代码不应依赖于错误,否则我会弄错吗? so i sat down and wrote this: 所以我坐下来写下:

    public static boolean checkInput(JTextField textField, int spielerGeld, String eingabe) {

    boolean matched = false;

    switch (eingabe) {

    case "num":
        if (!textField.getText().isEmpty() && textField.getText().matches("^[0-9]*$")) {

            int geldinput = Integer.parseInt(textField.getText());

            if (geldinput > 0 && geldinput < spielerGeld) {
                matched = true;
            }
        }
        break;

    case "string":
        if (!textField.getText().isEmpty() && textField.getText().matches("^[a-zA-Z]*$")) {
            matched = true;
        }
        break;

    default:
        break;
    }
    return matched;
}

Keep in mind, we yet dont have any textfields we have to check, but I just implemented it to get a grasp of how you could do multiple checks within one method. 请记住,我们还没有要检查的任何文本字段,但是我只是实现了它,以了解如何在一种方法中进行多次检查。

So now my question is, what code is "better"? 所以现在我的问题是,什么代码“更好”? and what could we/I do better? 我们能做得更好吗?

Thanks in advance! 提前致谢!

EDIT1: So as some already have mentioned, you say my method is not build up after the Single responsibility principle. EDIT1:就像已经提到的那样,您说我的方法不是建立在单一责任原则之后的。 But if split up into 'checkInputIsnumber' and checkInputIsString' would the first solution(my friend), still be the "better" one? 但是,如果将其拆分为“ checkInputIsnumber”和“ checkInputIsString”,第一个解决方案(我的朋友)仍然是“更好”的解决方案吗?

EDIT2: Better is defined as in, the method should be of low cyclomatic complexity, easy readability and be easy to maintain in the long run. 编辑2:更好地定义为,该方法应具有较低的圈复杂度,易读性并易于长期维护。

The first approach is much better than the second one. 第一种方法比第二种方法好得多。

  1. Single responsibility: You should avoid creating methods that do more than one thing. 单一职责:您应该避免创建做多事情的方法。
  2. Open–closed principle: Your 'validation' is not extensible. 开闭原则:您的“验证”不可扩展。 Try creating a Validator interface and then an implementation per validation type. 尝试创建一个Validator接口,然后创建每个验证类型的实现。
  3. Switch statements increase cyclomatic complexity and make testing harder. switch语句增加了循环复杂性,并使测试更加困难。

Also, don't use textField.getText() everywhere, it's quite possible that it will change between calls. 另外,不要在所有地方都使用textField.getText() ,它很有可能在两次调用之间改变。 Assign it to a local variable or even better use a String as your argument and not JText . 将其分配给局部变量,甚至最好使用String作为参数,而不是JText As Fildor pointed out you correctly avoid using exceptions for flow control and it is indeed better to have a single return point. 正如Fildor所指出的那样,您正确地避免使用异常进行流控制,确实最好有一个返回点。 Having said that, for simple cases when you just parse/check and return, it is acceptable. 话虽如此,对于简单的情况,只要您解析/检查并返回,就可以接受。

You should put every check in a single function. 您应该将每个检查都放在一个函数中。 After a while your "all in one function" will be unreadable an unmaintainable. 过了一会儿,您的“多功能一体机”将变得难以理解且难以维护。 Also it easier to change the checks if they are in single functions. 如果检查是在单个功能中,也更容易更改检查。 Using try/catch for control flow is no good idea. 对控制流使用try / catch并不是一个好主意。 It is expensive at runtime. 它在运行时很昂贵。 It is not a good style and most developers won't expect control flow in a catch block.Excpetions are for exceptional situations. 这不是一个好的样式,大多数开发人员都不希望在catch块中有控制流。

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

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