My standard datetime library didn’t have a standard way of saying “th” for days - you know, “Monday 1st April” vs “Tuesday 2nd April” vs “Wednesday 3rd April” vs “Any day xxth April probably”. So I went looking for solutions.
My favourite example was probably Lingua::EN::Numbers::Ordinate because of the way it iteratively works towards the proper solution:
sub ordsuf ($) {
return 'th' if not(defined($_[0])) or not( 0 + $_[0] );
# 'th' for undef, 0, or anything non-number.
my $n = abs($_[0]); # Throw away the sign.
return 'th' unless $n == int($n); # Best possible, I guess.
$n %= 100;
return 'th' if $n == 11 or $n == 12 or $n == 13;
$n %= 10;
return 'st' if $n == 1;
return 'nd' if $n == 2;
return 'rd' if $n == 3;
return 'th';
}
And the approach I least favoured, even though it’s far more “efficient”, was this one from Date::Format:
@Dsuf = (qw(th st nd rd th th th th th th)) x 3;
@Dsuf[11,12,13] = qw(th th th);
@Dsuf[30,31] = qw(th st);
It’s not just the way that it decides “let’s just do 0..9, 10..19, 20..29 automatically, then manually add 30 and 31” (presumably because that’s part of its data validation - if you ask it for an ordinal of 32 it will tell you that there’s no such day). Or the repetition of many “th” between 4 and 9.
It’s the fact that the programmer has decided “OK, what’s the problem?”, found a solution, and then decided “OK, how do we make the solution the most efficient possible?” and golfed their way towards the implementation. This is read-only code: it assumes that the problem has been solved, that this is the best way of solving it, and provides no information about why any of this ever happened (which is usually the way of finding bugs: to realise that the previous implementor’s approach was wrong).
The most annoying commonplace falsehood about programming is “it’s all about ones and zeroes”. It’s not: it’s been a lifetime since anyone actually programmed a computer by inputting ones and zeroes into anything. It might be ones and zeroes under the hood, but that’s as interesting as saying that the life as a materials chemist is all about quarks.
The second most annoying commonplace falsehood about programming is slightly more interesting: it says that programming is all about science, and maths in particular. That may be true in the more refined parts of our industry, but for the most part we’re writing systems that interact with humans rather than particle accelerators or lunar landers. And the way we write code should reflect that.
So: if your code is all about O(n) efficiency or what have you, by all means make it efficient. But if you’re just trying to deal with real-world problems, write the code in a way that resembles the real-world problem that you’re trying to solve. The future maintainer will thank you.
Leave a comment