I work in Java and Swift very often. Swift lends itself to writing fewer lines of code, which appeals to me because maintaining fewer lines of code always seems easier. But more importantly, fewer lines of code to do the same thing is more elegant, in my humble opinion.
Below is a small block of code I’m working on at work right now. This is some very old code written by someone else more than a few years ago. I added the “else” conditional block because a bug needed fixing:
Node lastFormValueNode = defaultNode.getFirstChildNode("LastFormValue");
if (lastFormValueNode != null && !StringUtils.isEmpty(lastFormValueNode.getCData())) {
sLastFormValue = lastFormValueNode.getCData();
} else {
sLastFormValue = sDefaultValue;
}
There is one issue with this that I dislike, which is that the getCData() function is called twice. I never feel comfortable leaving optimizations to the compiler and it’s also not always clear if the function call has any side effect. I try to never call the same function twice in this manner. If I want to remove one call to that function, the “if” test won’t work as expected, and I would need an extra level of nesting.
My solution reduces the overall number of lines of code from six down to three:
Node lastFormValueNode = defaultNode.getFirstChildNode("LastFormValue");
String valueData = lastFormValueNode == null ? null : lastFormValueNode.getCData();
sLastFormValue = StringUtils.isEmpty( valueData ) ? sDefaultValue : valueData;
This new code uses ternary operators to do more “if” testing than in the original code. This might make it a fraction of a millionth of a second slower. Still, I think the extra CPU cycles are worth it because now there is no visible “if” test and the code simply sets a few variables to various values depending on the state of previous variables.
Is this better source code? I think so since most code maintenance work involves a lot more work trying to understand and track down the section of code where a problem occurs and less analysis of individual lines. Ignoring the word-wrapping that might show up in this post and these new lines of code are better because the reader doesn’t need to parse the “if” test flow. Sure, the variables are set to different values based on conditions, but understanding the code is easier to do in this format, again in my humble opinion.