Matthijs C. de Jonge



When cleverness obscures your intentions

Generally speaking, writing code as a series of clever oneliners is a terrible idea. Elegant though they may seem, oneliners often (*) obscure the thing the code is actually trying to accomplish. Conventional wisdom therefore has it that oneliners should be avoided as they make it unnecessarily difficult for future maintainers to make changes to the code.

However, clever oneliners also make life difficult for the developer of the code while the code is being written. The reason is, again, that they obscure the thing the code is actually trying to accomplish. Consider this real life example:

my $unprocessedRecords = [$data->{'records'}] unless (ref($data->{'records'}) eq 'ARRAY');

What should happen here is that a reference to the contents of a data element called “records” goes into a variable called $unprocessedRecords. Owing to a quirk of the mechanism that created $data, however, $data->{’records’} may be either a reference to an array of records or to a single record, which is a hash. The developer, correctly, decided to make life easier for himself by ensuring $unprocessedRecords would always be a reference to an array, and since the developer in question (not me, though it could easily have been), wrote this oneliner to accomplish this.

What happened, therefore, was that several steps further on in the code, $unprocessedRecords turned out to contain no records at all and it took the developer almost half an hour worth of debugging for him to find and correct this mistake.

Now there is, of course, no shame, in producing bugs and taking a long time to find them. However, this particular bug (only if $data contained exactly one record would $unprocessedRecords contain records) would have easily been avoided had the developer written the code to explicitly match his intentions, like so:

my $unprocessedRecords = $data->{'records'};
$unprocessedRecords = [$unprocessedRecords] unless (ref($unprocessedRecords) eq 'ARRAY');

The lesson here is that your code should always match your intentions, even if it takes up more vertical space.

(*) except when they don’t