仅为了可读性而引入变量? [英] Introducing variables only for readability?

查看:132
本文介绍了仅为了可读性而引入变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

仅为了可读性而引入变量是一个好主意吗?

Is it a good idea to introduce variables only for the sake of readability?

示例1:

while(nameNode1.charAt(0) == nameNode2.charAt(0) && nameNode1.length() > 1 && nameNode2.length() > 1)
{
    nameNode1 = nameNode1.substring(1, nameNode1.length());
    nameNode2 = nameNode2.substring(1, nameNode2.length());
}

示例2:

boolean letterFromBothNodesAreEqual_andNameHasMoreThanOneLetter = nameNode1.charAt(0) == nameNode2.charAt(0) && nameNode1.length() > 1 && nameNode2.length() > 1;

while(letterFromBothNodesAreEqual_andNameHasMoreThanOneLetter)
{
    nameNode1 = nameNode1.substring(1, nameNode1.length());
    nameNode2 = nameNode2.substring(1, nameNode2.length());
}

这可能是一个极端的例子,但我想你明白了。

It might be an extreme example, but i think you get the idea.

我在代码中没有看到这个,我想知道这是否有用?

I haven't seen this in code and i was wondering if this is a useful approach?

谢谢

背景信息:我正在尝试从大学过渡到入门级开发人员,目前我专注于清洁编码。

Context: I'm trying to make the transition from college to Entry-Level-Developer and currently I'm focusing on clean-coding.

推荐答案

最好让代码可读,只是不要过多地做太多维护噩梦,尽管大多数干净代码都更容易维护。

It's always better to make code readable, just don't over do it too much where it's a maintenance nightmare, although most clean code is easier to maintain.

我会在这里介绍两种新方法而不是变量,代码示例如下:

I would introduce two new methods here instead of variables, where your code example would be:

while(letterFromBothNodesAreEqual() && nameHasMoreThanOneLetter())
{
    nameNode1 = nameNode1.substring(1, nameNode1.length());
    nameNode2 = nameNode2.substring(1, nameNode2.length());
}

这是一个常见的可读性重构,可以通过名称将布尔条件提取到自己的函数中。如果一个人正在阅读你的代码并遇到一些条件,那么他们就会想知道它的重要性是什么,为什么分支需要或它代表什么。单独的字段可能无法告诉他们答案,但如果条件具有名称(函数的名称),他们可能知道它代表什么。

It's a common readability refactor to extract boolean conditions into their own function with a name. If a person is reading your code and comes across some if with a bunch of conditions, they will wonder what the significance of it is, why is the branch needed or what it represents. The fields alone might not tell them the answer, but they might know what it represents if the condition had a name (the name of the function).

这篇关于仅为了可读性而引入变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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