Usually people tend to think that if a code has a low number of lines that it will be more easily to read and understand. A similar ideas is that a code that has a fewer number of lines will be faster.
In this post I will focus only on the first idea – code with a low number of line can be read and understand more easily.
JavaScript sample:
When I looked for the first time over this method I said something like: “Ouuhhh! What is the behavior of this method? … Ahhh, IF value is NULL then return an empty string. ELSE, IF the value is 0 then return ON, ELSE return OFF.
Good, now I understood this line of code. Even if the line looks cool, is not so simple to understand and can generate bugs very easily.
When you need to write something like this, don’t think that writing only one line of code will improve the code in one way or another.
In this post I will focus only on the first idea – code with a low number of line can be read and understand more easily.
JavaScript sample:
displayCustomValue: function (value) {
return value !== null ? value === 0 ? "ON" : "OFF" : "";
}
The cool thing is that it has only one line of code –one and powerful line of code. All of us know what a God class is. Based on this, we could say that our line of code from the method is a God line.When I looked for the first time over this method I said something like: “Ouuhhh! What is the behavior of this method? … Ahhh, IF value is NULL then return an empty string. ELSE, IF the value is 0 then return ON, ELSE return OFF.
Good, now I understood this line of code. Even if the line looks cool, is not so simple to understand and can generate bugs very easily.
When you need to write something like this, don’t think that writing only one line of code will improve the code in one way or another.
value !== null ? value === 1 ? value === 2 ? "? ": "1" : "2" : "null"
I would retrieve our method to something like this:displayCustomValue: function (value) {
if ( value === null )
{
return "";
}
if ( value === 0)
}
return "ON";
}
return "OFF";
}
Avoid using more than one “? :” per line in any programming language. Writing code with a lot of “? :” will increase the Ouuhhh factor.
That's from the same family as obfuscated C++ code: very compact, but easy to understand only by people very familiar with that syntax trick.
ReplyDelete