A short and quick example of some baffling coding today. It so happens this past weekend I was updating some HTML and CSS and JavaScript on this site. One of the JavaScript source files (luckily not written by me) had this:
function $$(id) {
if (id.substring(1, 0) != "#")
id = "#" + id;
return $(id)[0];
}
So, in other words, it takes an element id, makes sure it starts with a ‘#’, calls jQuery to return the elements with that id (of which there should be one only, of course), and then returns the DOM element for the first item in the jQuery object array. Not so bad, except…
1. ‘$$’ is a crap name for a function, sorry. Yes, I get that it calls jQuery, er, safely, but it just looks weird. And unlike $()
, it returns a DOM element and not a jQuery object. This caught me out elsewhere and is the topic of another post.
2. It uses ‘!=’ and not ‘!==’, something that rubs me up the wrong way in a Lint sense.
3. What the heck are those two parameters to substring()
? Yeah, I get that it’s getting the first character in the string, but that call just looks wrong.
That latter one actually got me to go to Mozilla Developer Network and look up the damn function. Look, there are two substring-type functions in JavaScript: substring()
and substr()
. The first gets a substring from a string given the starting index and the ending index (the character for which is not included in the returned substring), and the second gets a substring given the starting index and the number of characters. Already, we have to try and remember the calling syntax for two extremely similar functions, and also the edge cases for them both. For example, if the starting index for the first is less than 0, it’s assumed to mean 0; whereas if the starting index is less than 0 for the second, it’s assumed to count from the end of the string. See what I mean?
It turns out that substring()
has the nice behavior that if the ending index is less than the starting index, the function will swap them over before using them. Fine, I’d completely forgotten that fact, if I ever knew it anyway. But, why the hell the writer of this function didn’t call id.substring(0, 1)
, which I would have just understood implicitly (either as starting at 0 up to index 1, or, “wrongly”, as starting at zero for one character), I’ll never know. The parameters are hard-coded after all, and in a way to make the code maintainer stop and doubt his experience or sanity.
Bah.
No Responses
Feel free to add a comment...
Leave a response
Note: some MarkDown is allowed, but HTML is not. Expand to show what's available.
_emphasis_
**strong**
[text](url)
`IEnumerable`
* an item
1. an item
> Now is the time...
Preview of response