防御性编程和异常处理

发布于 2024-12-05 18:16:10 字数 342 浏览 1 评论 0原文

前几天,我在考试中遇到了以下理论问题: (a) 解释在处理以下问题时防御性编程的含义 执行过程中可能出现的特殊情况 程序。您可以参考课堂上看到的例子或使用伪 描述为防止某些情况而采取的步骤的代码 例如,在尝试读取文件时发生。 [5 分]

(b) 简要描述异常处理的含义 Java 中的内容以及这与防御性编程有何不同。 [5 分]

我一直认为防御性编程是编程的整个范式,异常处理是其中的一部分。 在考试期间,我写道,在“防御性编程”中,程序员尝试在执行逻辑代码之前找出所有可能的问题,然后从该函数返回错误值(示例0),而在异常处理中,潜在的错误发生并被捕获通过特殊的机制,这些错误被直接解释。对吗?正确答案应该是什么?

A couple days ago, I have following theoretical questions on the exam:
(a) Explain what is meant by defensive programming when dealing with
exceptional circumstances that may occur during the execution of a
program. You may refer to examples seen in class or use pseudo
code to describe the steps taken to prevent certain circumstances
from occurring when trying to read a file for example.
[5 marks]

(b) Briefly describe in general terms what is meant by exception handling
in Java and how this differs from defensive programming.
[5 marks]

I always thought that defensive programming is the whole paradigm of programming and that exception handling is the part of it.
During exam I write that in "defensive programming", programmer try to find out all possible problems before executing the logic code, and later on return error value(example 0) from this function, whereas in exception handling the potential errors occurs and are caught by special mechanism, in which these errors are directly being interpreted. Is it right? What should be correct answers?

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

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

发布评论

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

评论(2

2024-12-12 18:16:10

对我来说,防御性编程意味着编写代码来处理您认为不会甚至不会发生的情况,因为您相信自己的信念不可靠。

例如(未编译或测试,条款和条件适用):

private String findSmallestString(Collection<String> strings) {
    if (strings == null || strings.isEmpty()) return null;
    Iterator<String> stringsIt = strings.iterator();
    try {
        String smallestString = stringsIt.next();
        while (stringsIt.hasNext()) {
            String candidateString = stringsIt.next();
            if (candidateString == null) continue;
            if (candidateString.compareTo(smallestString) < 0) {
                smallestString = candidateString;
            }
        }
        return smallestString;
    }
    catch (NoSuchElementException e) {
        return null;
    }
}

其中,可以说是防御性功能包括:

  • 顶部的 null 或空保护条款;这是一个私有方法,因此您应该能够确保永远不会使用 null 或空集合
  • 来调用它。您可以证明,如果迭代器履行其约定,则它包含的代码永远不会抛出此异常。
  • 来自迭代器的字符串(第一个除外!)的无效保护子句;同样,由于这是一个私有方法,您应该能够确保集合参数不包含空值(无论如何,您将做什么将空值放入集合中?)

并不是每个人都同意空值检查是防御性的。 try-catch 已经到了完全没有意义的程度。

对我来说,防御性编程的严峻考验是你认为防御永远不会被使用。

Defensive programming, to me, means writing code to handle cases that you do not think will, or even can, happen, because you have a belief that your own beliefs are unreliable.

For example (not compiled or tested, terms and conditions apply):

private String findSmallestString(Collection<String> strings) {
    if (strings == null || strings.isEmpty()) return null;
    Iterator<String> stringsIt = strings.iterator();
    try {
        String smallestString = stringsIt.next();
        while (stringsIt.hasNext()) {
            String candidateString = stringsIt.next();
            if (candidateString == null) continue;
            if (candidateString.compareTo(smallestString) < 0) {
                smallestString = candidateString;
            }
        }
        return smallestString;
    }
    catch (NoSuchElementException e) {
        return null;
    }
}

In there, arguably defensive features include:

  • The null-or-empty guard clause at the top; this is a private method, so you should be in a position to ensure that it is never called with a null or empty collection
  • The try-catch for NoSuchElementException; you can prove that the code it contains will never throw this exception if the iterator fulfils its contract.
  • The nullity guard clause on the strings (other than the first!) coming out of the iterator; again, since this is a private method, you should probably be able to ensure that the collection parameter contains no nulls (and what would you be doing putting nulls in collections anyway?)

Not everyone would agree that the null checks are defensive. The try-catch is, to the point of being completely pointless.

For me, the acid test of defensive programming is that you don't think the defence will ever be used.

流殇 2024-12-12 18:16:10

对我来说,防御性编程是假设最坏的情况:你的用户是完全疯狂的人,你必须保护自己和你的程序免受他们疯狂输入的影响。我相信这句话中蕴藏着很多智慧:

软件行业每天都在制造更大、更好的傻瓜软件,而大自然也每天都在制造更大、更好的傻瓜。到目前为止,自然获胜

,永远不要忘记您的用户不仅仅是您的客户。如果您负责库 API,您的用户可能是其他部门。在这种情况下,我一生中听到的最尖锐的抱怨之一是:

即使我们删除了所有失败的单元测试,程序仍然无法运行

For me defensive programming is assuming the worst case: that your users are complete crazy people and you must defend yourself and your program from their crazy inputs. I believe there is a lot of wisdom within this quote:

Every day, the software industry is making bigger and better fool-proof software, and every day, nature is making bigger and better fools. So far nature is winning

And never forget that your users are not only your clients. If you are responsible of a library API your users might be other department. In that case one of the most stellar complains I ever heard in my life was:

Even after we deleted all failed unit tests, the program did not work

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