5 Best Practice Mentalities to Get Over

By  on  

Every developers strives to write clean, maintainable, and functional code, whether they hack on the server side or dabble on the client side. Over the last few decades of the web, we've learned from some of our early mistakes and formed a site of always changing best practices. These best practices usually keep us out of trouble but some of them are taken way too literally, to the point where developers become too rigid and borderline crippled by them. Truth be told, with these best practices are mostly good to follow, they're broken not out complacency but by necessity. Here are five best practices that aren't quite as realistic as we'd like to think.

"Don't Add Globals to window"

JavaScript developers go to great lengths to encapsulate their code, like creating classes, closures, and modules. I agree with the mentality that you should avoid globals, but sometimes you simply have to. I recommend creating one global object named after the project name (Dojo Toolkit uses dojo and Groupon's Groupon object) and tagging properties on that. Creating an army of globals can get you into trouble but adding a few globals to window is just fine, if not unavoidable. As long as you know the environment your code will run in, you won't run into naming collision problems.

"Adding to Native Prototypes is Bad"

The early JavaScript frameworks like Prototype and MooTools first gained popularity because they empowered native object prototypes. No longer did you write globally available functions to modify instances of String, Number, Array, Object, Function, etc -- you could pin methods on the prototype for each so that every existing and future instance had those methods; a total boost to productivity and code efficiency. Then after a few new naming collusions due to standard and proprietary web and browser API implementations, developers turned on the practice, to the point where the thought of adding a method to a native prototype meant you should turn in your developer credential badge.

Much with adding a global to the window, adding methods to a native object's prototype is fine done correctly. Name your new method properly (i.e. don't give your method a common name) and you'll be just fine. I'm not telling you to do this a lot, I'm simply saying that adding a method to a prototype isn't going to bring your career to a screeching halt.

"Never Use UA Sniffing"

User agent sniffing has gotten a rotten name because it was originally used to sniff features, and we know how badly that turned out. Believe it or not though, UA sniffing is still used by most large websites to detect mobile and then forward users to the mobile version of a site. And you know what? It's reliable and in the best interests of our users. I've been asked "What if the user spoofs the user agent?" My reply is "Then they get whichever site view that comes with it, so who cares? They've done this on purpose and if they get a dysfunctional site it's their problem." As long as you provide a link to the desktop version of the site, you'll be just fine.

"It's OK to Load [JavaScript Library] From CDN Because the User will Likely Have Loaded it Already"

This one really burns me, especially after my trip to Brazil to promote Firefox OS. Yes, loading utilities from CDN is fast and, provided enough people use the CDN, there's a decent chance the user has the code cached, but it isn't that simple. Assuming a site has jQuery cached, for example, is risky because there are numerous versions and subversions and subsubversions being used at any given time. If the user doesn't have an unlimited data plan (which isn't offered in most countries), they could be paying quite a bit for each site that uses a JavaScript library or site which loads large files, CDN or not. When I went to Brazil, I would have to pay 20 cents for just jQuery if I went to a site using it. Long story short: assuming users don't pay a penalty for a CDN-hosted resource is a bad, bad mentality.

"Pixel Perfection is a Must"

Quality designers and developers tend to be perfectionists, that's why they do well. We do, however, get caught up in pixel perfection when we translate from design to working page -- likely because pixel perfection is achievable. The problem in focusing on pixel perfection is that the obsession leads to a lot of time that isn't enhancing the user experience, it's enhancing our ego. Of course other designers and developers will come to the site and notice the odd width or height issue, but 90+% of users would prefer we make performing a given task easier, not ensuring each column measures precisely. Of course I'm not advocating you create "landmine" sites with pixels off everywhere, but sometimes you need to file a bug to fix later and keep making your site more usable, accessible, and fun!

It's important that we don't lose sight of practicality when we try to stick to best practices. We can look sternly at a certain practices but what's most important is that we create functional, usable web sites. Never accept a rule without questioning its total validity and never be afraid to step outside rigid trains of thought!

Recent Features

Incredible Demos

Discussion

  1. Pragmatism FTW!

  2. Barry Wood

    If the site needs jQuery, using a CDN at least provides the opportunity that the library is already cached in the browser. If you just link to a copy on the site that guarantees that it will have to be downloaded. Am I missing the point of your post on that point?

    • I’m saying not to include jQuery for minor stuff that could be accomplished with pure JS or a tinier, more focused library.

    • Newton

      @david, glad I looked in the comments, because that’s not abundantly clear by the title. “It’s OK to Load [JavaScript Library] From CDN Because the User will Likely Have Loaded it Already” leads me to believe this is about CDNs and not about using pure JS instead of a library for small things.

  3. One small nit: since the Dojo Toolkit made the transition to AMD, the only *real* globals used are the methods “require” and “define”. Or at least that’s the theory ;)

  4. Cthos

    Can you elaborate a bit on the cost model for Brazilian internet access? Is that *just* accessing jQuery from a CDN, or are they just paying that in transfer fees?

  5. The CDN point doesn’t make any sense. Any decent CDN uses version numbers in their urls.

    What does brazil have to with anything? I guess they pay regardless of whether the request is to a CDN; then what difference does it make to your argument about CDNs? If anything, you _should_ use a CDN for the off-chance the file will be cached by the user’s browser, so that they pay less, right?

    I don’t see how using a CDN would ever be a drawback. It’s wrong to assume a CDN means cached files, but there’s nothing inherently wrong with using one. Specially if you’re using one of the well-established CDN’s out there like Google’s, MSFT’s, etc

    • Ling

      When I recall it correctly in Brazil (perhaps South America in general) a huge amount of the internet traffic goes over mobile networks, so there are higher costs for the consumers.

  6. To be clear, I’m not saying that developers shouldn’t use CDNs. I’m saying developers shouldn’t use CDNs as an excuse to load a big library instead of a smaller one.

    • Ling

      I read that mobile browsers don’t cache that much to preserve the lifetime of the flash memory of the device. Since you work at Mozilla is that a fact (at least regarding the mighty Fox/Panda)?

  7. What are some examples that you have used of adding methods to native prototypes, other than polyfilling features like ES5 in older browsers?

  8. Chris Reed

    Not using globals is kindness to other developers that will be editing your code. They represent a failure to abstract your design pattern with a client (as in trigger set or control, not a person or employer).

    “Adding to Native Prototypes is Bad” === “Not Encapsulating Modules is Good”. javaScript has all of the tools it needs to interact with the browser. Any specific functionality you are adding should be a part of your design pattern and therefore encapsulated.

  9. Loupax

    Only a Sith speaks in absolutes, but here goes:

    “Don’t Add Globals to window” => “Don’t Accidentally Add Globals to window”

    “Adding to Native Prototypes is Bad” => “Adding to Native Prototypes is Risky if you don’t take into account what the browser might support next”

    “Never use UA sniffing” => “Never use UA sniffing if what you want to get is a single feature of that UA”

    The “It’s OK to Load [JavaScript Library] From CDN Because the User will Likely Have Loaded it Already”
    is a bit misleading of a title though. It is as OK, as sending from your own CDN/Server. Not more, not less

  10. Yes, I totally agree with the UA sniffing point, they’ll get the experience designed for that of course! And the pixel perfection issue is definitely worth sticking to.

    Good post, thanks!

  11. Bah, I totally disagree with this post, and you couldn’t even come up with some examples to back up your points.

    Adding to Native Prototypes is not “Bad”, but it is potentially risky and should be done only for polyfills.

    Don’t Add Globals to window IS bad, and that’s why you yourself suggest adding them to a global object attached to window (of course there must be at least ONE var attached to window)

    It’s OK to Load [JavaScript Library] From CDN Because the User will Likely Have Loaded it Already
    This is complete nonsense. If you are serving a site from the internet users will have to pay to download it, whether it comes from CDN or wherever. What has Brazil got to do with anything?
    If you meant to say “don’t make users download jQuery if you are only doing something small and simple because it may cost them money” then write “don’t make users download jQuery if you are only doing something small and simple because it may cost them money”. Plus if a user can’t afford to download an extra 40k because they are roaming or something, what are they doing surfing the internet?

  12. Evan

    Yeah kind of a weak point about libraries and CDNs… If you need jQuery, you need jQuery. Might as well load it from a CDN because it might be a bit faster and they just might have it cached already.. Also, if it’s 20 cents for 50k of data you shouldn’t be surfing or you can afford it…

  13. I’m confused on the CDN point (as are many others).

    First of all – if there are plans out there that cost 20 cents to load 50K, how can the user even be surfing the web at all? I looked up the cost of some smartphone plans in Brazil and it seems like even the most expensive plans are around 0.002 Brazilian reals for 50K. (http://prepaidwithdata.wikia.com/wiki/Brazil). So that’s two orders of magnitude off?

    If your argument is that a smaller library is better, talking about CDNs just obscures the point.

    Surely this is an empirical question; is it actually an advantage to load libraries from CDN (on the assumption that you will “share” a library with other sites the user already downloaded). There must be studies about this.

  14. Corey Alix

    Wouldn’t has(“dojo”, “1.9.*”) be great? Will we ever be able to Install complete toolkits right into the browser?

  15. Vinicius

    Bulls***, except for the obvious pixel perfect part

  16. Revin Guillen

    Best practices for library/toolkit code are different for application code anyway. Too many folks gloss over that distinction and get too religious about things that don’t really matter.

  17. I like what you had to say, but I think you could have said the CDN part a little better. I get it. I think what you’re going for is “Don’t download a large library like jQuery if you’re not going to use most of it”. Downloading the library just to hide and show elements on the page is wasteful. If you’re going to use it to animate transitions, make xhr requests, and seriously modify the DOM, it’s worth it.

    That’s the story that Dojo tried to tell. When they went to AMD, you didn’t need to download the whole dojo object, just the modules you need.

  18. What you’ve said about CDN doesn’t make any sense. Furthermore, I live in Brazil and I pay USD 12 monthly to have unlimited internet on my smartphone!
    Another problem is that people come to Sao Paulo or Rio de Janeiro and they think the whole Brazil is like that. Here in Southern Brazil, we live in a different Brazil!

    • Ling

      USD 12 and unlimited traffic? Lucky one! I’m paying EUR 15 for 500 MB / mont in Germany :-(

  19. Today, you can get jQuery from half a dozen of CDNs, so the chance the copy you have in cache comes from a previously used CDN isn’t great. And if that’s the case, chances are one site is using v. 2.9 while the next one uses v. 2.11… :-)

    So “use CDNs for caching” is probably wrong. You can still use them for faster delivery (if the speed of the CDN is higher than the one of your own site; likely with shared hosts) and to reduce bandwidth usage of your site (some shared / free sites throttle it).

    Beside, indeed, getting jQuery out of laziness, to avoid a pair of document.getElementsByClassName or equivalent, is an offence! :-D

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!