DEV Community

Anders Björkland

Posted on

I work with web development daily. It is one of my joys, but can also be a source of great frustration. A recent frustration tracking down some logic in a third-party library led me to a discovery. It was a method declaring void as its return-value. Reasonably, one would assume that it wouldn't return any value as such. Maybe it would mutate a value, but that was all. Was this the case though? NO.

The method would parse some input value and then it would throw its calculated value out into the abyss, hoping there would be a catch-statement somewhere that would handle it.

I don't know if this is a common pattern and if it has any name. I suggested to one of my colleagues that we name it "the anti prop-drill": it isn't a prop, it isn't passed through step-by-step, and it is thrown in an opposite direction. I'm open to hear your suggestions, or maybe make me understand if this is a reasonable pattern.

Anyway, this inspired me to write the ugliest (and funniest) code I have ever written. This is exceptional coding!

``````<?php

function sum(array \$array)
{
\$sum = 0.0;

try {
\$i = 0;
while(true) {
\$value = \$array[\$i] ?? throw new \Exception('' . \$sum);
\$sum += \$value;
\$i++;
}
} catch (Exception \$e) {
return (float)\$e->getMessage();
}
}

\$values = [3, 2.5, 0.5];
echo 'Sum of ' . implode(' + ', \$values) . ' = ' . sum(\$values) . PHP_EOL;
``````

Output: `Sum of 3 + 2.5 + 0.5 = 6`

PHP doesn't automatically throw an "Array Index out of Bound" Exception. Instead it returns null. So `\$array[\$i] ?? throw new \Exception` checks if the value is null and if so it will throw a new exception with our `\$sum` wrapped in its message.

What is the ugliest code you have achieved?