Which is better, declarative or shorter code?
TL;DR: Be declarative enough but no more.
-
Readability
-
Use a short version (or not).
-
Always favor readability >> Premature optimization.
-
Humans learn by examples, not by formulas.
-
Shorter is not always better.
Last week, a tweet went viral because of a missing formula.
%[https://twitter.com/JeroenFrijters/status/1615204074588180481]
It is the DigiD digital authentication iOS app in the Netherlands.
private static string GetPercentageRounds(double percentage)
{
if (percentage == 0)
return "⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪";
if (percentage > 0.0 && percentage <= 0.1)
return "🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪";
if (percentage > 0.1 && percentage <= 0.2)
return "🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪";
if (percentage > 0.2 && percentage <= 0.3)
return "🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪";
if (percentage > 0.3 && percentage <= 0.4)
return "🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪";
if (percentage > 0.4 && percentage <= 0.5)
return "🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪";
if (percentage > 0.5 && percentage <= 0.6)
return "🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪";
if (percentage > 0.6 && percentage <= 0.7)
return "🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪";
if (percentage > 0.7 && percentage <= 0.8)
return "🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪";
if (percentage > 0.8 && percentage <= 0.9)
return "🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪";
return "🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵";
}
}
}
// Full source
// https://github.com/MinBZK/
// woo-besluit-broncode-digid-app/
// blob/master/Source/DigiD.iOS/Services/NFCService.cs
private static string GetPercentageRounds(double percentage)
{
string dots = "🔵🔵🔵🔵🔵🔵🔵🔵🔵🔵⚪⚪⚪⚪⚪⚪⚪⚪⚪⚪";
int blueDots = (int) Math.Truncate (percentage* 10);
int startingPoint = 10-blueDots;
return dots. Substring(startingPoint, 10);
}
[X] Semi-Automatic
This is a semantic smell. In this case, we can count the number of if clauses.
- Readability
You can read the original Twitter thread to take your own conclusions. There's some serious debate and, of course, several premature optimizators bringing obscure and unneeded solutions with (O) log(n) complexity and stupid benchmarks evidence for a loop that executes only once.
And lots of memes.
As a final conclusion, I asked ChatGPT and was not able to simplify it.
Code Smell 36 - Switch/case/elseif/else/if statements
Code Smell 20 - Premature Optimization
%[https://twitter.com/JeroenFrijters/status/1615204074588180481]
How to Get Rid of Annoying IFs Forever
Code Smells are just my opinion.
There are two ways of constructing a software design. One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.
C. A. R. Hoare
Software Engineering Great Quotes
This article is part of the CodeSmell Series.