删除 if 语句的嵌套
我有一段代码,我不知道如何重构它。它的可读性不是很好,我想让它可读。这是一个问题,
数据库中有两列,它们可以是 NULL、0 或每列都有一个值。在网页上,这两列中的每一列都有一个复选框 - 启用和文本框 - 值。
x = checkbox1
z = textbox1
y = checkbox2
w = textbox2
逻辑是,如果两个复选框均未选中,则两个值都应为 0。如果其中一个被选中而另一个未选中,则其他值应为 NULL。对于所选的文本框,如果文本框为空,则其值应为 NULL,否则应为文本框中的值
if{x}
{
if(z)
{
a = NULL;
}
else
{
a = z;
}
if(y)
{
if(w)
{
b=w;
}
else
{
b = NULL;
}
}
else
{
b = null
}
}
else
{
if(y)
{
a = NULL;
if(w)
{
b=w;
}
else
{
b = NULL;
}
}
else
{
a = 0;
b = 0;
}
}
相信我,这是一个有效的场景。让我知道这是否有意义或者我应该提供更多信息
I have a piece of code, which I am not sure how to refactor.. It is not very readable and I would like to make it readable. Here is a the problem
There are two columns in database which can be either NULL, 0 or have a value each. On the web page there is a checkbox - enable and text box - value for each of those two columns.
x = checkbox1
z = textbox1
y = checkbox2
w = textbox2
The logic is if both the checkboxes are not selected, then both the values should be 0. If either one is selected and other is not, then others value should be NULL. and for the one that is selected, if the textbox is empty its value should be NULL else should be the value in the textbox
if{x}
{
if(z)
{
a = NULL;
}
else
{
a = z;
}
if(y)
{
if(w)
{
b=w;
}
else
{
b = NULL;
}
}
else
{
b = null
}
}
else
{
if(y)
{
a = NULL;
if(w)
{
b=w;
}
else
{
b = NULL;
}
}
else
{
a = 0;
b = 0;
}
}
Trust me this is a valid scenario. Let me know if this makes sense or I should give more information
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用一些逻辑与和非,我们得到更具可读性的东西。
我们可以通过默认为 NULL 来节省一点(因此不需要将另一个设置为 NULL)。我们还可以通过将检查文本框是否已设置或使用 null 的代码放入一个小函数中来节省。
在伪代码中:
Using some logical ands and nots, we get something more readable.
We can save a little by defaulting to NULL (thus not needing to set the other to NULL). We can also save by putting the code for checking if a textbox is set or using null into a little function.
In pseudo code:
我认为使用比这里的单个字母更具描述性的名称会有所帮助,但假设这是 C 代码,那么使用内联 if 语句看起来会更整洁:
I think it would help to use more descriptive names that the single letters here, but assuming this is C code, it looks a lot neater with inline if statements: