你怎么让错误的代码看起来错误?你使用什么模式来避免语义错误? [英] How do you make wrong code look wrong? What patterns do you use to avoid semantic errors?

查看:219
本文介绍了你怎么让错误的代码看起来错误?你使用什么模式来避免语义错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

自从我第一次在中做一个作业的错误时,如果我总是写这样的ifs:

Ever since I first made the mistake of doing an assignment in an if I've always written my ifs like this:

if (CONST == variable) {

if (variable = CONST) { //WRONG, assigning 0 to variable

自从我读了Joel Spolsky的文章错误代码看起来很错我一直在努力把他的建议付诸实践。

And since I read Joel Spolsky's essay Making Wrong Code Look Wrong I've been trying to put his advice into practice.

那么,你使用什么其他模式来使错误的代码看起来错误,或者如果你犯了一个语义错误,强制语法错误?

So what other patterns do you use to make wrong code look wrong, or to force syntactic errors if you make a semantic mistake?

推荐答案

我发现让错误的代码看起来错误,对编译器来说非常重要。 在实践中(并且仅当使用强类型语言时),这意味着省略任何种类的变量前缀(甚至Apps Hungarian),以支持不同类型。要使用Joel的例子,如果有两个不同的类型来表示原始字符串和清理过的字符串,并且两者之间没有隐式转换,那么Apps Hungarian无法解决的问题。

I find it important to make wrong code look wrong to the compiler. In practice (and only when using strongly typed languages), this means omitting any kind of variable prefixes (even Apps Hungarian) in favour of distinct types. To use Joel's example, if there are two distinct types to represent raw strings and sanitized strings, and there's no implicit conversion between the two, then the problem that Apps Hungarian addresses can't even occur.

这同样适用于Word文档坐标。在某种程度上,Apps Hungarian仅仅是没有严格足够类型检查的编译器/语言的解决方法。

The same goes for the Word document coordinates. In a way, Apps Hungarian is only a workaround for compilers/languages that have no strict enough type checking.

这篇关于你怎么让错误的代码看起来错误?你使用什么模式来避免语义错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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