by nonchalance · 13y ago · 0 comments
The true problem here lies with the poor choice of function name on the part of the original author and lack of commentary. The name "formatted_zip_code" automatically primes people to expect that you passed a (possibly mal-formed) zip code and the function should format it properly. Under that metric, the original code was indeed deficient and should have been changed. Whether it retained the original style is secondary, but there were clear functional deficiencies.
"Anything with fewer than three digits is supposed to be an invalid code" is not reflected in the code (why does it return digits and not trigger an error there?) and apparently there are no comments, so it should be no surprise that it needed to be fixed.
I've seen this kind of code time and again from coworkers who have the "code should be self-documenting" mentality, who refuse to put in comments explaining why they wrote a function a particular way. But what they think is self-documenting, very, very, very rarely is to others.
The whole tale is just "if it ain't broke, don't fix it."
I struggle between this and the accumulation of technical debt. Sure, it's not broken... but that doesn't mean it can't be improved.
def formatted_zip_code(digits)
case digits.size
when 4 then "0#{digits}"
when 3 then "00#{digits}"
# 2 or less digits is an invalid input
else digits
end
end-> if the argument doesn't conform to contract, an assert/exception should be thrown so that the caller can recognize the existence of an incorrectly used function.
Normally I'd agree with your argument about failing to meet a contract, but why would this formatter method get anything but a valid zip code.
Ask not, lest ye receive an answer.
Seriously speaking, you can't trust that callers will be sane unless you establish a priori with a higher level contract that all possible callers will be sane.