Skip to content

Instantly share code, notes, and snippets.

@cgcardona
Last active August 27, 2015 18:04
Show Gist options
  • Save cgcardona/e8c21c4e52126b0fb5c0 to your computer and use it in GitHub Desktop.
Save cgcardona/e8c21c4e52126b0fb5c0 to your computer and use it in GitHub Desktop.

Striking a balance between terseness and understandability

Intro

Often when calling a function I will attempt to boil the code down to the most terse expression possible. However I've noticed that when working w/ a team there is a balance to be struck between terseness and understandability.

So a nonsensical example might be

var MyObj = {
    postData: function(amount, headline) {
        console.log('called w/', amount, headline);
    }
};

Here we have a super basic javascript object literal w/ a function which takes an amount and a headline and does something w/ them.

Terseness

If I were working alone and needed to call this API I would write something like the following.

$('.btn').click(function(evt) {
    MyObj.postData(evt.currentTarget.dataset.amount, $('#headline').text());
});

Here we are binding a click event to some buttons on the screen and when they are clicked we call the postData function and pass in the amount and the headline.

Though notice that my first argument is a property 3 objects deep on the evt object which is returned when the button's click event is fired.

Similarly the headline is text which is returned by calling jQuery's document.getElementById and .text() APIs.

Understandability

Of course the above code isn't that hard to read but when you have particularly complex APIs you can sacrifice a bit of terseness to add a bunch of readability by doing something like the following.

$('.btn').click(function(evt) {
    var amount = evt.currentTarget.dataset.amount;
    var headline = $('#headline').text();
    MyObj.postData(amount, headline);
});

Note that I've simply moved the lines of code out from being passed in as arguments and put them in variable declarations above the postData function call.

Then when I call postData I pass in the variable names which match the original method definition above. MyObj.postData(amount, headline);

Small steps like this go a long way when helping new engineers on-ramp to a new code base.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment