Language shortcuts can often be used to make code more concise. For example, ter
ID: 639283 • Letter: L
Question
Language shortcuts can often be used to make code more concise.
For example, ternary and null coalescing operators can reduce the amount of code, but arguably to the detriment of readability:
In C#:
Person newGuy = new Person();
if (boss == null) {
newGuy.Boss = GetDefaultBoss();
} else {
newGuy.Boss = boss;
}
is functionally equivalent to:
Person newGuy = new Person();
newGuy.Boss = boss ?? GetDefaultBoss();
but obviously a lot more verbose.
Where do you draw the line when it comes to conciseness vs readability?
Explanation / Answer
Both.
Your first example is certainly more verbose, and arguably more explicit... but it also requires me to scan five lines instead of one. Worse, it deemphasizes its purpose - assigning a value to newGuy.Boss.
Your second example may cost me a second if I'm unfamiliar with the null coalescing operator, but there can be no doubt as to its purpose, and if I'm scanning through a larger routine looking for the source of a value, it will be much easier for me to pick this one out.
Now, contrast this:
if (boss == null) {
newGuy.Boss = GetDefaultBoss();
newGuy.IsTemp = true;
newGuy.AddTask("orientation");
} else {
newGuy.Boss = boss;
newGuy.IsTemp = false;
}
...with:
newGuy.Boss = boss ?? GetDefaultBoss();
newGuy.IsTemp = boss == null;
if ( boss == null ) newGuy.AddTask("orientation");
The latter example is again much shorter, but now it obscures its purpose by making tasks triggered by the same test appear to be distinct. Here, I feel the verbosity of the former is justified.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.