• Share
  • Email
  • Embed
  • Like
  • Save
  • Private Content
7 Deadly Sins of JavaScript
 

7 Deadly Sins of JavaScript

on

  • 1,921 views

A brief overview of JavaScript coding practices, with depraved gummy bears! ...

A brief overview of JavaScript coding practices, with depraved gummy bears!

Presentation given to a mixed developer audience. Introduces some specific gotchas of the language, mentions design patterns like module and observer, and discusses general good programming practice and refactoring.

Gummy bear photography provided by http://www.flickr.com/photos/wiedmaier/ under a limited CC license.

Statistics

Views

Total Views
1,921
Views on SlideShare
1,917
Embed Views
4

Actions

Likes
2
Downloads
17
Comments
0

2 Embeds 4

http://www.slideshare.net 3
http://www.docshut.com 1

Accessibility

Categories

Upload Details

Uploaded via as Microsoft PowerPoint

Usage Rights

© All Rights Reserved

Report content

Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
  • Full Name Full Name Comment goes here.
    Are you sure you want to
    Your message goes here
    Processing…
Post Comment
Edit your comment
  • This will be some general good coding practices, along with JavaScript-specific tips. Good coding practice can keep code running quickly, help with maintainability, create more useful APIs, and save kittens.
  • Starting with the most evil thing you can do in javascript. Usually on an epic scale (global namespace). It’s easy to create globals, intentionally or accidentally. JavaScript operates in a browser. JavaScript also does not have block scope, only function scope. It’s very easy to clobber the global namespace and create conflicts.
  • Both awesum and hai are created globally. isCaturday is scoped to the block by javascript, but others are not.
  • There are two solutions. First, use a namespace for methods. Second, remember to always declare vars within functions with the var keyword.
  • Accidental creation of globals is all too common. If more than one party does it, we have a real problem. Remember, js is function scoped only, so i and il are both global.
  • Declare iterators along with other vars, and you no longer clobber the global namespace.
  • Envy is wanting someone else’s stuff. There are several ways this can work in JavaScript, and the first has to do with the way prototype inheritance works.
  • Every object inherits from Object, and functions inherit from Function which inherits from Object. If some third party has added to those prototypes (dangerous in my opinion, but prototype and mootools both do this), you will get all those properties along with the ones actually a part of fud. There is a solution:
  • hasOwnProperty checks and filters out anything that’s not a direct property of the object. ALWAYS use this. It’s a well-spent extra line of code. Remember, even if it doesn’t break without hasOwnProperty today, it will break tomorrow if someone adds to the Object prototype.
  • Not only envy of another’s stuff, but also of another’s role. Front end code works best when each piece respects the other’s turf. JavaScript can change css properties, but it’s a very inflexible way to do things, and it’s not really JavaScript’s job. This code prevents using a different visual treatment, like opacity. It also mucks with anything that might need to read the object’s width and height on the page, since these properties aren’t available on items with display:none.
  • Instead, set a class, and use CSS to style per the requirements. This way, you can set it off-screen if code needs to modify width an height, or you can set opacity if the requirements change from hiding completely.
  • More functionality envy: This is fuzzier, but in general it’s best to extract anything whose functionality could change. This is especially important in third party scripts – you don’t want their implementation to be tied to your core code. If the NOT_CN API ever changes, the library which this code is in will need to be changed. If another third party script ever needed to be hit here, code would need to be put in here to use it also.
  • Instead, fire an observer and place the third party code into the implementation. The side benefit is that you have an observer fired that can be used for other purposes also.
  • Lust is lack of self-control or self-restraint.
  • This object is nice, it encapsulates a ceilingCat, including properties and methods. However, it indecently exposes things that should not change, like the altitude of the cat.
  • If we refactor to use the module pattern, we can have a closure which returns only what should be public. Since the ceiling altitude doesn’t change, we have only a getter. Never leave something public if it doesn’t need to be.
  • Greed is hoarding, or storing too much stuff.
  • This method is hoarding parameters. Long param lists are easy to fall into but they are ugly and they lead to errors. This method is clear because the var names are good, but the call is confusiong. We have to refer to the method to figure out what the three params are for, plus passing null into methods doesn’t look nice.
  • If we restructure to use an object with options, it’s much clearer. Both the method and the implementation are clear about the params, and the implementation doesn’t need to specify things that aren’t necessary. Also, though I’m not showing it, you can overload methods if necessary. If options is really a function when checked with typeof, you have a signature that takes a callback and an optional second param would then be the object. if it’s an object, you know it’s the only param.
  • Don’t hoard the this object. This code will require implementation of multiple lines to set multiple properties.
  • Three lines, and we have to look up myBukkit as many times as we need to access it.
  • Instead, return this. Now the implementation can be done in one line.
  • Here it is.
  • Gluttony is traditionally defined as wastefulness.
  • It’s easy to create anonymous functions that do too much. This is very common code to see, because jQuery just makes it so easy! But it’s evil. This is just an example; you can imagine this anonymous function getting much longer.
  • Now, we call a method, which means that something else can disturb the cat too and the same result will happen. If need be, we could pass a type of disturbance into the method.
  • Multiple var declarations make code harder to read.
  • Don’t waste, just use one var declaration. Don’t forget to declare iterators if you’re using them!
  • Using a var when it’s unnecessary is wasteful. This code is clear, but the li and the position are used only once.
  • The refactoring dispenses with two vars and is more readable as well.
  • Serious wastefulness comes with duplicate code. I’ve left out the details to get it to fit, but assume the three methods are nearly identical, with only the ul class and the hash location different.
  • Instead, use a create method to encapsulate that logic. Notice the try/catch in case the API is misused.
  • Now each type of nav can call the create method and provide the details it needs. Notice I should refactor the param list; it works but isn’t pretty.
  • Apathy is a catchall in some ways, but includes things we just don’t always take the time to do. Like a good scout, leave the campground better than when you arrived. This won’t show refactorings; most are familiar to us and we just need the reminder to take a few minutes to make the world a better place. And save kittens.
  • Occasionally this kind of nesting is hard to avoid, but it’s all too common…
  • Switch is an interesting case (*rimshot*). JavaScript is much more forgiving than other languages – switch doesn’t need to be typesafe, no enums, break isn’t required, but this doesn’t mean you should take advantage of the looseness. There’s very little reason to not use a break – if you want the fallthrough you should probably extract a method. If your var can be many different types, you probably have some other refactoring to do. if you have a very long switch, you’re probably taking an ugly shortcut.
  • This can be controversial especially if you don’t have many unit tests, but there’s always dead code that can be removed. For example, legacy addEvent calls can be rewritten to use jQuery. Code that deals with APIs that aren’t used anymore can be removed. Take the time to grep for calls to the code in question. See if it’s used. Ask someone. If it’s really inconclusive, leave it, but most of the time you’ll be able to get rid of something that is cluttering up the codebase.
  • Names are important. Bandwidth is important. But we have minificiation and gzip. Think about the hours of time that someone will be paid down the road to figure out what you meant, and just choose good names now.
  • Try/catch is a double-edged sword. Code like this is a bad idea. if you’re not sure about something, figure it out, don’t just throw in a try block – it is fairly slow in most JavaScript engines.
  • However, my rule of thumb is to use try/catch when I’m writing an API. If you need to have a certain thing passed in to a public API, you need to check what it is. Sometimes the easiest way to do that is with a try/catch block. But use with care.
  • Ending with pride. Traditionally this was though to be the greatest sin, essentially wanting to be god, or take the place of god.
  • So what better to talk about than god objects? I’m not going to show examples, because we all know that we do it. Especially in javascript, it’s very easy to write 200 lines and try to do everything in one block. It may work, but it is not fun to read or to maintain. While refactoring, you often will discover common/duplicate code, and end up with many methods, most under 10 lines. One method can’t do everything.
  • A few tips for refactoring god objects.
  • Challenge yourself to refactor JavaScript code. It will make it easier for you to come back to in 6 months, and it will make life easier for those who have to deal with your code down the road. You’ll also learn more about the language and its expressiveness. I hope this was helpful. Go and sin no more.

7 Deadly Sins of JavaScript 7 Deadly Sins of JavaScript Presentation Transcript

  •  
  •  
  • 1. Wrath
    • Anger, hatred, usually on an epic (global?) scale
  •  
  •  
  •  
  •  
  •  
  • 2. Envy
    • Wanting what another has
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  • 3. Lust
    • Lack of self-control
  •  
  •  
  •  
  • 4. Greed
    • Hoarding of goods
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  • 5. Gluttony
    • Wastefulness
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  • 6. Apathy
    • Lack of care or concern
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  • 7. Pride
    • Wanting to be God
  •  
  •  
  •