使用 JavaScript 进行断言式编程 [英] Assertive programming with JavaScript

查看:45
本文介绍了使用 JavaScript 进行断言式编程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道为什么断言式编程很好,所以我想将它与 JavaScript 结合使用.但是,我不想向用户显示错误框,这是不寻常的事情.忽略它并让他们重试可能会更好.

I know why assertive programming is good, so I want to use it with JavaScript. However, I don't want to show users error boxes, and it's unusual thing. Just ignore it and make them retry could be better.

例如这段代码会产生一个错误框并中断用户.

For example this code will make an error box and interrupt users.

function getDomainFromURL(url) {
    assertTrue(url, 'URL should not be null');

    ...parsing
}

所以,我会这样做.

function getDomainFromURL(url) {
    if (!url) return;

    ...parsing
}

我认为第二个有利于可用性,第一个有利于开发.因此,IMO 最好将这些结合起来并使 assert 在生产代码中消失.

Second one is good for usability, I think, and first one is good for developing. Therefore, IMO it would be the best to combine these and make the assert disappear on production code.

问题 1你是这样认为的吗?或者有什么不同的想法?

Question 1 Do you think so? Or have any different idea?

问题 2如果你这么认为,用Spring3框架有什么好的办法吗?

Question 2 If you think so, is there any good way to do it with Spring3 framework?

推荐答案

我不认为第二个特别好.如果您从始终期望返回某些内容的方法中不返回任何内容,则代码可能只会在其他地方失败,而不是接近实际问题所在的位置,即在 getDomainFromURL 函数内.

I don't think the second one is particularly good at all. If you return nothing from a method that is always expected to return something, the code will likely just fail somewhere else, instead of close to where the actual problem is i.e. within the getDomainFromURL function.

另一方面,如果这个方法在参数为空时不返回任何内容是完全可以的,那么添加断言是没有意义的.

If on the other hand, it's perfectly OK for this method to return nothing when the parameter is null, then it doesn't make sense to add the assertion.

就我个人而言,无论是在开发还是生产中,我都会在任何地方使用第一种形式.如果断言在生产中失败,那么您将获得关于问题原因的非常有用的反馈(在浏览器、日志等中).如果您删除断言,您仍然会遇到错误,但会更难以追踪

Personally, I would use the first form everywhere, in both development and production. If the assertion fails in production, then you'll get very useful feedback (in the browser, logs, etc.) about the cause of your problem. If you remove the assertion, you'll still have a bug, but it'll just be more difficult to track down

这种编程风格 - 检查前提条件 - 是所谓的基于契约的编程的一部分.我以前从未听说过断言式编程"这个词.

This style of programming - checking pre-conditions - is part of what is known as contract-based programming. I've never heard of the term "assertive programming" before.

这篇关于使用 JavaScript 进行断言式编程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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