Is it a good idea to introduce variables only for the sake of readability
?
Example 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());
}
Example 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?
Thank You
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).