简体   繁体   English

检查参数的更好方法?

[英]Better way to check Parameters?

In various situations I'm confronted with the problem, that I need to check the parameters of a function to guarantee a correct program flow. 在各种情况下,我都会遇到这个问题,我需要检查一个函数的参数以确保正确的程序流程。

I found that it is becoming to be a bit tedious to create if-else blocks just to check for nullpointer, ranges of numbers, correct strings, correct objects and so on. 我发现创建if-else块只是为了检查nullpointer,数字范围,正确的字符串,正确的对象等变得有点乏味。 Besides the code becomes more difficult to read and thus it becomes more difficult to have the overview. 此外,代码变得更加难以阅读,因此拥有概述也变得更加困难。

So I thought what if there is a way in java/javascript/c#... (programming languages with functions in it) where you can define some pre-conditions. 所以我想如果在java / javascript / c#...中有一种方法(可以在其中编写带有功能的语言)可以定义一些前提条件。

So for eg in java: 因此,例如在Java中:

  void doSomething( int a {0 <= a < 10}, String b {b != "wrong" && b != [1-9]}){
   ...
  }

or something like this: 或类似这样的东西:

  §a: 0 <= a && 10 > a || a == 25 ...
  §b: ...
  §ifWrongPreConditions: return; //or throw a new default Exception or whatever
  void doSomething( int a, String b){
    §a: 0 <= a && 10 > a || a == 25 ...
    §b: ...
    §ifWrongPreConditions: return; //or throw a new default Exception or whatever
  ...Code...
  }

or above the method head. 或方法头上方。 Basically the second idea could help for post-conditions too and you only need one look at the function to know what you need to do so that the function is working correct. 基本上,第二个想法也可以为后置条件提供帮助,您只需要看一下函数就可以知道自己需要做什么,以使该函数正常工作。

But I'm not sure if there is something like already implemented, but I want to have it a little easier to become an overview over the "meta-info" of a function so can anticipate the desired and undesired behavior and it might be easier to make it work with OCL. 但是我不确定是否已经实现了某些功能,但是我想让它更容易成为功能的“元信息”的概述,以便可以预期所需的和不希望的行为,并且可能会更容易使它与OCL一起使用。

So back to the question: Is there a good way to define Pre-, Post-Conditions, maybe Invariants for methods (maybe classes and similar stuff) that are easy to read in the respective language? 回到问题所在:是否有一种很好的方法来定义前置条件,后置条件,或者定义易于使用相应语言阅读的方法(可能是类和类似内容)的不变式?

(PS Im not sure if the tags I set here are "correct", because it is a practical question for different languages about a concept that might confront programmers in those languages. Sorry in advance for that) (PS Im不确定我在此处设置的标签是否“正确”,因为对于不同的语言来说,这是一个可能会遇到使用这些语言的程序员的概念的实际问题。对此表示抱歉)

Java has no argument validation feature in the JDK. Java在JDK中没有参数验证功能。 However, there is specification for Bean Validation which has similar capabilities. 但是,存在具有类似功能的Bean验证规范 and there are 3rd party libraries and frameworks that implement above mentioned specification. 并且有实现上述规范的第三方库和框架。 One of the popular frameworks is Spring which has a module for annotation based Validation Spring是流行的框架之一,它具有用于基于注释的验证的模块。

Here is an example for such validation: 这是这种验证的示例:

package hello;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class PersonForm {

    @NotNull
    @Size(min=2, max=30)
    private String name;

    @NotNull
    @Min(18)
    private Integer age;

    public String getName() {
        return this.name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String toString() {
        return "Person(Name: " + this.name + ", Age: " + this.age + ")";
    }
}

Answering for Java first. 首先回答Java。 There we have bean validation : 那里我们有bean验证

  • you use a declarative approach, by using annotations on the "data structures" that your code will be using 您使用声明性方法,即在代码将使用的“数据结构”上使用注释
  • you then have some framework "in the background" that takes care of validating actual data against the declared expectations 然后,您将拥有一些 “在后台”的框架,该框架用于根据声明的期望来验证实际数据

The essential thought here: you absolutely do not validate data structures "manually". 重要思想在这里:你绝对验证数据结构“手动”。 Instead, you establish a notation that can be applied to such structures, and then you have a generic framework to turn declarations into runtime checks. 相反,您可以建立一种可应用于此类结构的表示法,然后拥有一个通用框架将声明转换为运行时检查。

JavaScript has similar ideas, see the validatejs library for example. JavaScript有类似的想法,例如请参见validatejs库。

And of course, same things exist in C#, too. 当然,C#中也存在相同的东西。 See this SO question for example. 这个例如SO问题。

Assertions are a fairly standard cross-language approach. 断言是一种相当标准的跨语言方法。 The nice thing about assertions is that, in most environments, you can include them for testing, but turn them off for release builds on the theory you've found the bugs they defend against. 关于断言的好处是,在大多数环境中,您可以包括它们以进行测试,但是要根据已发现它们可以防御的错误的理论将其关闭以进行发布。 For that reason, assertions are not the way to handle user input, of course. 因此,断言当然不是处理用户输入的方法。

Java has direct support for them ( assert ), as does the .Net platform ( Debug.Assert ). Java和.Net平台( Debug.Assert )一样直接支持它们( assert )。 JavaScript doesn't have direct support for assertions, but they're readily added with a utility function, or you could write a Babel plug-in for them that compiles the assertion to nothing for release builds. JavaScript没有对断言的直接支持,但是很容易为它们添加了实用程序功能,或者您可以为它们编写Babel插件,以将断言编译为发布版本。

assert example: assert示例:

void doSomething(int a, String b) {
    assert a >= 0 && a < 10;
    assert !b.equals("wrong") && /*...your second condition didn't make sense for strings */;
}

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

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