使用断言或异常按合同设计? [英] Design by contract using assertions or exceptions?

查看:30
本文介绍了使用断言或异常按合同设计?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当通过契约编程一个函数或方法时,首先检查其先决条件是否得到满足,然后再开始履行其职责,对吧?进行这些检查的两种最突出的方法是通过 assert 和通过 exception.

When programming by contract a function or method first checks whether its preconditions are fulfilled, before starting to work on its responsibilities, right? The two most prominent ways to do these checks are by assert and by exception.

  1. assert 仅在调试模式下失败.确保(单元)测试所有单独的合同先决条件以查看它们是否真的失败是至关重要的.
  2. 在调试和发布模式下异常失败.这样做的好处是经过测试的调试行为与发布行为相同,但会导致运行时性能损失.

你觉得哪个更好?

查看相关问题这里

推荐答案

在发布版本中禁用断言就像在说我在发布版本中永远不会有任何问题",但通常情况并非如此.所以断言不应该在发布版本中被禁用.但是您也不希望发布版本在发生错误时崩溃,对吗?

Disabling assert in release builds is like saying "I will never have any issues whatsoever in a release build", which is often not the case. So assert shouldn't be disabled in a release build. But you don't want the release build crashing whenever errors occur either, do you?

所以要使用异常并用好它们.使用良好、可靠的异常层次结构并确保您捕获并可以在调试器中对异常抛出进行挂钩以捕获它,并且在发布模式下您可以补偿错误而不是直接崩溃.这是更安全的方式.

So use exceptions and use them well. Use a good, solid exception hierarchy and ensure that you catch and you can put a hook on exception throwing in your debugger to catch it, and in release mode you can compensate for the error rather than a straight-up crash. It's the safer way to go.

这篇关于使用断言或异常按合同设计?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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