patternjavascriptMinor
shorthand methods
Viewed 0 times
methodsshorthandstackoverflow
Problem
Is it good or bad practice (or, when is it appropriate) to use shorthand methods?
Lets pretend we're using jQuery here, because it has a lot of them.:
These are all really just shorthand forms for the ajax function, with the exception of load which combines another function later on.
I can use
This to me seems insane, and overly complicates the API. Is this good, or bad, or what? Why isn't there a getCSS and a PostCSS and a postScript and a putScript too?
Lets pretend we're using jQuery here, because it has a lot of them.:
jQuery.ajax()
jQuery.get()
jQuery.getJSON()
jQuery.getScript()
.load()
jQuery.post()These are all really just shorthand forms for the ajax function, with the exception of load which combines another function later on.
I can use
$.ajax( dataType: 'script',) to do the same thing as getScript, but why?This to me seems insane, and overly complicates the API. Is this good, or bad, or what? Why isn't there a getCSS and a PostCSS and a postScript and a putScript too?
Solution
Hm, good question. I guess I would say that the number one rule of programming is DRY: Don't Repeat Yourself. You could argue that any function is "just shorthand for" whatever it does. But whenever you find yourself typing the same thing over and over and over, even if that thing is only two or three lines, it's worth at least asking yourself, should I make this into a function?
Now the authors of JQuery don't know exactly what kind of code you're writing, they just have a general idea of what JavaScript code out there in the world looks like. So maybe they originally just had
so why not shorten it up a little bit?
I agree it's possible to overdo it though, and have a zillion little functions that are all variants of the same idea, making the API seem overwhelming. So it's a question of finding the right balance, I guess.
Now the authors of JQuery don't know exactly what kind of code you're writing, they just have a general idea of what JavaScript code out there in the world looks like. So maybe they originally just had
$.ajax() and then over time they realized, you know, 99% of the time, people are either doing always GETs or always POSTs, it's rare that you do something like:var method;
if (someComplicatedThing()) method = 'GET';
else method = 'POST';
$.ajax({method:method});so why not shorten it up a little bit?
I agree it's possible to overdo it though, and have a zillion little functions that are all variants of the same idea, making the API seem overwhelming. So it's a question of finding the right balance, I guess.
Code Snippets
var method;
if (someComplicatedThing()) method = 'GET';
else method = 'POST';
$.ajax({method:method});Context
StackExchange Code Review Q#2214, answer score: 3
Revisions (0)
No revisions yet.