本文介绍了Java中的LBYL与EAFP?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近自学 Python 并发现了 LBYL/EAFP 习语,用于在代码执行前进行错误检查.在 Python 中,似乎接受的样式是 EAFP,并且似乎与该语言配合得很好.

I was recently teaching myself Python and discovered the LBYL/EAFP idioms with regards to error checking before code execution. In Python, it seems the accepted style is EAFP, and it seems to work well with the language.

LBYL(Look Before You Leap):

LBYL (Look Before You Leap):

def safe_divide_1(x, y):
    if y == 0:
        print "Divide-by-0 attempt detected"
        return None
    else:
        return x/y

EAFP(E更容易Ask Forgiveness than Permission>):

EAFP (it's Easier to Ask Forgiveness than Permission):

def safe_divide_2(x, y):
    try:
        return x/y
    except ZeroDivisionError:  
        print "Divide-by-0 attempt detected"
        return None

我的问题是:我从来没有听说过使用 EAFP 作为主要数据验证构造,来自 Java 和 C++ 背景.在 Java 中使用 EAFP 是否明智?还是异常带来的开销太大?我知道只有在实际抛出异常时才会产生开销,所以我不确定为什么不使用更简单的 EAFP 方法.只是偏好吗?

My question is this: I had never even heard of using EAFP as the primary data validation construct, coming from a Java and C++ background. Is EAFP something that is wise to use in Java? Or is there too much overhead from exceptions? I know that there is only overhead when an exception is actually thrown, so I'm unsure as to why the simpler method of EAFP is not used. Is it just preference?

推荐答案

就我个人而言,而且我认为这是由惯例支持的,EAFP 从来都不是一个好的方法.您可以将其视为等效于以下内容:

Personally, and I think this is backed up by convention, EAFP is never a good way to go.You can look at it as an equivalent to the following:

if (o != null)
    o.doSomething();
else
    // handle

相反:

try {
    o.doSomething()
}
catch (NullPointerException npe) { 
    // handle
}

此外,请考虑以下事项:

Moreover, consider the following:

if (a != null)
    if (b != null)
        if (c != null)
            a.getB().getC().doSomething();
        else
            // handle c null
    else
        // handle b null
else
    // handle a null

这可能看起来不那么优雅(是的,这是一个粗略的例子 - 请耐心等待),但它在处理错误时为您提供了更大的粒度,而不是将其全部包装在 try-catch 中以获取该错误NullPointerException,然后试着找出你在哪里以及为什么得到它.

This may look a lot less elegant (and yes this is a crude example - bear with me), but it gives you much greater granularity in handling the error, as opposed to wrapping it all in a try-catch to get that NullPointerException, and then try to figure out where and why you got it.

在我看来,永远不应该使用 EAFP,除非是极少数情况.此外,由于您提出了这个问题:是的,即使没有抛出异常,try-catch 块也会产生一些开销.

The way I see it EAFP should never be used, except for rare situations. Also, since you raised the issue: yes, the try-catch block does incur some overhead even if the exception is not thrown.

这篇关于Java中的LBYL与EAFP?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-18 18:14