是否可以通过括号防止死亡? [英] Is it possible to prevent death by parentheses?

查看:81
本文介绍了是否可以通过括号防止死亡?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有时,我会写一些带有比我更多的括号的代码.

Occasionally, I will write some code with way more parentheses than I like.

 if(!(new Day((((new Date()) / millisecondsPerDay) % 75)) instanceof oldDay))) { 
    // Bonus points if that condition made any sense to you
 }

很难跟踪需要插入多少个括号,尤其是当我没有使用IDE时,当出现问题时它会立即告诉我.实际上,我敢打赌,上面的示例与括号不正确匹配.与死亡有关的错误中,括号所引起的错误比我所允许的还要多.

It is hard to keep track of how many parentheses I need to put, especially when I'm not using an IDE that immediately tells me when something is wrong. In fact, I bet the above example doesn't match the parentheses correctly. I've been pegged with errors from death by parentheses more than I would like to admit.

我想知道是否有办法避免这种情况.我可以使用什么技术来避免必须用太多的括号将内容包装起来?

I was wondering if there was a way to circumvent this. What techniques can I use to avoid having to wrap things with so many parentheses?

有没有一种语言可以防止使用太多的括号?例如,我认为添加可以自动将所有括号括起来的特殊字符和一个自动将其打开的特殊字符可能会有所帮助. (在下面的示例中为<>)

Are there any languages with a mechanism that prevent the need for so many parentheses? For example, I thought adding special characters that automaticall close parentheses and one that automatically opens them might help. (< and > in the following example)

if(!(new Day<new Date()) / millisecondsPerDay) % 75> instanceof oldDay>

推荐答案

一种可行的选择是在条件循环之前预先计算括号内的值.以您的代码为例:

One viable alternative is to precompute the parenthesized values before the conditional loop. Take your code for example:

if(!(new Day((((new Date()) / millisecondsPerDay) % 75)) instanceof oldDay))) { 
    // Bonus points if that condition made any sense to you
 }

让我们开始分解它.

Date d1 = new Date();
var factor1 = (d1 / millisecondsPerDay ) % 75;
Day day1 = new Day (factor1);

if (!day1 instanceof oldDay) {
// do something
}

请记住,代码是供人类阅读的,之后才供机器执行.如果发现巨大的条件,则开始对其进行预处理并将其分解.如果要花超过一秒钟的时间弄清楚您的状况正在检查,则可能太长了.

Remember that code is written for humans to read and only afterwards for machines to execute. If you find giant conditionals, then start preprocessing them and break it up. If it takes more than a second to figure out what your condition is checking, then it's probably too long.

这篇关于是否可以通过括号防止死亡?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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