进行函数参数检查的干净方法(或模式)是什么?

发布于 2024-11-02 23:24:37 字数 661 浏览 0 评论 0原文

是否有任何设计模式或干净的方法来进行函数/方法参数检查(针对允许的值)?

目前,我的函数中的许多初始代码都由这些参数检查(空字符串、无效字符、现有 id 等)组成,虽然有必要,但它有点丑陋,并且混淆了函数的“真实”代码。通常,我的代码是这样的:

def my_function(p1,p2,p3,p4):
    #check parameters
    if p1 == ''
       raise InvalidArgError('p1 can not be empty')
    if p1 not in valid_list:
       raise InvalidArgError('p1 does not exist')
    if p2 < 0:
       raise InvalidArgError('p2 can not be negative')
    ...

    #finally do something
    p = p2+p3

对于解决方案,我沿着 装饰器。
我正在使用Python,尽管我认为一个好的解决方案是与语言无关的。

Is there any design pattern or clean way to do function/method parameter checking (against allowed values)?

Currently, lots of the initial code in my functions consists of these parameter checks (empty strings, invalid characters, existing id, ...) and, while necessary, it is a bit ugly and obfuscates the 'real' code of the function. Typically, my code goes something like this:

def my_function(p1,p2,p3,p4):
    #check parameters
    if p1 == ''
       raise InvalidArgError('p1 can not be empty')
    if p1 not in valid_list:
       raise InvalidArgError('p1 does not exist')
    if p2 < 0:
       raise InvalidArgError('p2 can not be negative')
    ...

    #finally do something
    p = p2+p3

For the solution, I am thinking along the lines of decorators in Python.
I am using Python, although I guess a good solution would be language-independent.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

心舞飞扬 2024-11-09 23:24:37

目前我能想象到的唯一与语言无关的事情是某种代码契约,这样你就可以做这样的事情:

func foo(param1, param2)
{
    Contract.NotNull(param1)
    Contract.IsIn(0, 100, param2)
}

我假设你可以在大多数编程语言中提出某种实现。

更新

Microsoft 正在实施Java 实现

The only fairly language independent thing I can imagine at the moment is some kind of code contract so you can do things like:

func foo(param1, param2)
{
    Contract.NotNull(param1)
    Contract.IsIn(0, 100, param2)
}

I assume you could come up with an implementation of some sorts in most programming languages.

Update

Microsoft is working on an implementation and there is a Java implementation.

静待花开 2024-11-09 23:24:37

方法的每个参数代表一个实体。对于方法/整个类工作所依据的参数值,必须存在一些约束或假设。所以我编写了方法来检查这些参数的有效性。

void drawRectangle(int length, int width) {
    if (isValidLength(length) == false || isValidWidth(width) == false) {
        // log about invalid argument so that it can be easily traced for debugging
        return;
    }

    // remaining  code
}

boolean isValidLength(int length) {
    if (value < 0 || value > 100) {
        return false;
    }

    return true;
}

优点是避免重复代码。如果在多个方法中对同一参数类型进行空值检查、范围检查,有时由于需求修改而导致该参数的范围发生变化,则需要在多个地方进行更改。另一方面,如果检查是在单独的方法中完成的,则更改的范围会减少。

Each parameter of a method represents an entity. There must be some constraints or assumptions about the argument values based on which the method/the whole class works. So I write methods for validity check of those parameters.

void drawRectangle(int length, int width) {
    if (isValidLength(length) == false || isValidWidth(width) == false) {
        // log about invalid argument so that it can be easily traced for debugging
        return;
    }

    // remaining  code
}

boolean isValidLength(int length) {
    if (value < 0 || value > 100) {
        return false;
    }

    return true;
}

The advantage is avoiding duplicate code. If null checking, range checking is done for the same parameter type in several methods and sometime later the range for that parameter changes due to requirements modification, then changes are to be made in several places. On the other hand, if the check is done in a separate method, scope of change reduces.

春风十里 2024-11-09 23:24:37

我想不是真的,不是统一的方式来做到这一点。

我个人在我的函数中澄清了这一点:如果要完成大量参数检查(随机示例),则真正的代码从哪里开始:

def setpoint(x, y):
    # checking for out of bounds
    if x < 0 or x >= maxwidth: return false
    if y < 0 or y >= maxheight: return false

    # start function
    map[x][y] = true

也许您应该考虑将函数拆分为更小的函数,以分散参数检查。

I guess not really, not one uniform way to do it.

I personally clarify it in my functions where the real code starts if there is alot of parameter checking to be done (random example):

def setpoint(x, y):
    # checking for out of bounds
    if x < 0 or x >= maxwidth: return false
    if y < 0 or y >= maxheight: return false

    # start function
    map[x][y] = true

Perhaps you should consider splitting your functions up in smaller functions, to spread the parameter checking.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文