Introducing variables only for readability?

那年仲夏 提交于 2019-12-06 04:55:31

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).

biziclop

Apart from the fact that the variable name in your example is a bit too verbose, yes.

One thing that is important though is to remember to keep the scope of local variables as small as possible. So don't declare local variables at the start of the method if they're only going to be used in an if block further down.

Edit: And one more thing I've just noticed: your two examples are NOT equivalent. In the first scenario the expression is recalculated on every iteration, in the second one it isn't. In cases like this you need a helper method as explained by @NESPowerGlove instead of a variable.

Yes offcourse its a good practice to name variables according to there work or functionality in the program.Because in case in the future if someone else works on your code then it will be easier for him to understand otherwise it will give him a headache same happens while working on distributed program your co-workers must understand variables work by there name.

This question is quite subjective but the following holds true for all subjects. (I wanted to have a little fun with this answer)

private boolean isMoreReadable = true;
private boolean isEasyToMaintain = true;
private boolean isProperlyCommented = true;
private boolean isBugFree = true;

// This method checks if my co-workers are happy with my code
private boolean myCoWorkersHappyWithMyCode() {
    return isMoreReadable && isEasyToMaintain && isProperlyCommented && isBugFree;
}

if (myCoWorkersHappyWithMyCode()) {
    System.out.println("YES, you wrote good code so I don't see why not");
} else {
    System.out.println("NO, keep learning to better yourself");
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!