大学网 > php中文网 > 后端开发Why I always assign intermediate values to local variables instead of passing them directly to function calls正文

Why I always assign intermediate values to local variables instead of passing them directly to function calls

中国大学网 2024-10-17

而不是

def do_something(a, b, c):
    return res_fn(
        fn(a, b),
        fn(b),
        c
    )

我愿意:

def do_something(a, b, c):
    inter_1 = fn(a, b)
    inter_2 = fn(b)

    result = res_fn(inter_1, inter_2, c)
    return result

第一个版本要短得多,如果格式正确,同样具有可读性。

但我更喜欢第二种方法的原因是因为所有中间步骤都保存到局部变量中。

像sentry这样的异常跟踪工具,甚至是设置debug=true时弹出的django错误页面,都会捕获本地上下文。最重要的是,如果您必须使用调试器单步执行该函数,您可以在单步执行该函数之前看到确切的返回值。这就是为什么我什至在返回最终结果之前将其保存在局部变量中的原因。

以几个额外的变量赋值和几行额外的代码为代价,这使得调试变得更加容易。

以上就是Why I always assign intermediate values to local variables instead of passing them directly to function calls的详细内容,更多请关注中国大学网其它相关文章!