Simple Code Tasks Should Be Simple
Mike Stemle
Posted on September 29, 2020
I frequently see people do simple things in the most complicated ways with dynamic languages. I suspect much of this is a carry-over from how we teach algorithms and programming in universities. If you want your code to be readable, and you want it to be maintainable long-term, then simple code tasks should be simple.
Merging Two Lists
This is simple. You've got a list of fruits, and a list of vegetables, and you want to merge them into a list called "produce."
In Perl:
my @fruits = qw/apple banana mango/;
my @veggies = qw/broccoli asparagus spinach/;
In JavaScript:
const fruits = ['apple', 'banana', 'mango']
const veggies = ['broccoli', 'asparagus', 'spinach']
Some folks will want to use iteration, or even a push()
function of some sort here, but neither is necessary. A simple assignment statement will work just fine.
In Perl:
my @produce = (@fruits, @veggies);
In JavaScript:
const produce = [...fruits, ...veggies];
Not very impressive, I know, but watch what happens when I do the same thing with associative arrays (a.k.a. Object
s, a.k.a. hashes). Now we're going to have produce items, with their colors.
In Perl:
my %fruits = (
apple => 'red',
banana => 'yellow',
mango => 'light-orange');
my %veggies = (
broccoli => 'green',
asparagus => 'green',
spinach => 'green');
my %produce = (%fruits, %veggies);
In JavaScript:
const fruits = {
apple: 'red',
banana: 'yellow',
mango: 'light-orange'}
const veggies = {
broccoli: 'green',
asparagus: 'green',
spinach: 'green'}
const produce = {...fruits, ...veggies};
It's super cool to have slick code that does neat things, but when it comes to squishing data together keeping things simple is always better.
One Exception: When you're using JavaScript, the spread operator (...
) is limited to the maximum limit supported by Function.apply()
, which (as of the time of this post) is 65,536 total values.
Anyway, I had fun writing this and I hope that your code brings you joy.
Posted on September 29, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.