编程风格:应该检查函数中是否存在null或函数中是否存在null? [英] Programming style: Should you check for null in functions or out of functions?

查看:65
本文介绍了编程风格:应该检查函数中是否存在null或函数中是否存在null?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在调用带有对象的函数时,应在调用函数之前还是在调用两者之前检查函数中是否为null?什么是更好的编程实践?

When you call a function with a object, should you check for null in the function, before calling the function or both? What is better programming practice?

类似这样的东西

Test a = getTest();

if (a != null) {
    myFunc(a);
}

def myFunc(x):
    print x.val();

Test a = new Test();

myFunc(a);

def myFunc(x):
    if (x != null) {
        print x.val();
    }

Test a = new Test();

if (a != null) {
    myFunc(a);
}

def myFunc(x):
    if (x != null) {
        print x.val();
    } 

我可以理解为什么将null检查放入函数中是很好的,因为那样您不必在所有地方进行检查,但是有时您需要在调用函数之前进行检查,因此检查两次会感到多余...

I can see why putting the null check in the function is good, because then you don't have to check everywhere, but sometimes u need to check before calling the function, so then it feels redundant to check twice...

有人可以解释吗?

推荐答案

我认为这取决于代码的预期用途和/或分布.这实际上是基于观点的,但是我同意Bob叔叔关于防御性编程"的观点.如果它是供您使用或供团队使用的库,那么您应该避免防御性编程,毕竟您相信您的同事不会将null传递给函数吗?

I think it depends on the intended use and/or distribution of the code. This is really based on opinions but I agree with Uncle Bob's opinion on "Defensive programming". If it's a library for your use or your team's use, you should avoid defensive programming, after all you trust your coworkers to not pass null into a function right?

但是,如果您正在编写供任何人使用的公共API,则应进行适当的检查,尤其是在传递null可能导致崩溃的情况下.

If however you're writing a public API which may be used by anyone, you should make the proper checks, especially where passing null could cause a crash.

在非公共API中的防御性编程既有气味又有症状, 不执行TDD的团队.

Defensive programming, in non-public APIs, is a smell, and a symptom, of teams that don't do TDD.

@unclebobmartin

@unclebobmartin

这篇关于编程风格:应该检查函数中是否存在null或函数中是否存在null?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆