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.
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.
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.