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

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

问题描述

在合同编程时,一个功能或方法首先检查其先决条件是否得到履行,然后才开始履行职责,对吗?执行这些检查的两个最突出的方法是通过断言异常

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. 断言仅在调试模式下失败。要确保(单位)测试所有单独的合同前提条件,以确定它们是否真的失败至关重要。

  2. 异常在调试和释放模式下失败。这样做的好处是,测试的调试行为与发布行为相同,但会导致运行时性能损失。

你认为哪一个更好吗?

请参阅相关问题此处

推荐答案

在发布版本中禁用断言就像发布版本中永远不会有任何问题,这通常是不是这样所以在发布版本中不应该禁用assert。但是,您不希望发生错误时发生崩溃,是吗?

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天全站免登陆