Successfully reported this slideshow.
We use your LinkedIn profile and activity data to personalize ads and to show you more relevant ads. You can change your ad preferences anytime.

Maintainable JavaScript

16,654 views

Published on

Explains how to write JavaScript in a way that creates the most value for your company, making it maintainable.

Published in: Technology

Maintainable JavaScript

  1. 1. Maintainable JavaS cript Nicholas C . Zakas S r. Frontend E ngineer, M y Yahoo!
  2. 2. Why? Writing New Code Maintaining Code
  3. 3. Who cares ? • Your employer • Your co-workers, present and future • D evelopment community
  4. 4. What is maintainability? • Understandable • Intuitive • Adaptable • E xtendable • D ebuggable
  5. 5. C ode C onventions M aintainable JavaS cript
  6. 6. R eadable code • Indent your code • C omment your code – E ach method – Large sections of code – D ifficult-to-understand algorithms – Hacks
  7. 7. Naming • Use logical names for variables and functions – D on’t worry about length • Variable names should be nouns (i.e., car) • Function names should begin with a verb (i.e., getName()) – For functions returning Boolean values, prefix with “is”, such as isValid() • Avoid useless names such as foo, bar, temp
  8. 8. Indicate variable type • Initialization var found = false; • Hungarian Notation var sName = quot;Nicholasquot;; • Type C omments var cost /*:float*/ = 5.23;
  9. 9. Loos e C oupling M aintainable JavaS cript
  10. 10. C lient-s ide Layers Behavior Presentation (JavaScript) (CSS) Structure (HTML)
  11. 11. S eparate HTML and JavaS cript • JavaS cript in HTM L <a onclick=quot;sayHi()quot;>text</a> • HTM L in JavaS cript element.innerHTML = quot;<div>quot; + quot;<a href=quot;/js/quot;>text</a></div>quot;;
  12. 12. S eparate C S S and JavaS cript • JavaS cript in C S S div.hd { width: expression(ref.offsetWidth+quot;pxquot;); } • C S S in JavaS cript element.style.color = quot;redquot;;
  13. 13. E vent handlers handle events function handleKeyPress(event){ if (event.keyCode == 13){ var value = 5 * parseInt(txt.value); div.innerHTML = value; alert(quot;Updatedquot;); } }
  14. 14. E vent handlers handle events function handleKeyPress(event){ if (event.keyCode == 13){ performCalculation(); updateUI(); } }
  15. 15. Prog ramming Practices M aintainable JavaS cript
  16. 16. Don’t Modify Objects You Don’t Own • D on’t add methods • D on’t override methods • You don’t own O bject, Array, R egE xp, S tring, Number, B oolean, D ate, Function
  17. 17. Avoid g lobals • All publicly-accessible functions/ variables should be attached to an object • Namespace your objects – D on’t go overboard – Three levels is enough YAHOO.Way.Too.Long.Namespace
  18. 18. Don’t overus e popular techniques • C losures/nested functions – Use sparingly • O bject literals – S ingletons – P ass data
  19. 19. Throw your own errors function add5(value) { if (arguments.length < 1) { throw new Error(quot;add5: Not enough argsquot;); } return value + 5; }
  20. 20. Avoid null comparis ons function sortArray(value) { if (value != null) { value.sort(); } }
  21. 21. Avoid null comparis ons function sortArray(value) { if (value instanceof Array) { value.sort(); } }
  22. 22. Avoid null comparis ons function sortArray(value) { if (value instanceof Array) { value.sort(); } else { throw new Error(quot;sortArray: argument must be an array.quot;); } }
  23. 23. Avoid null comparis ons • Use instanceof for specific types of objects if (value instanceof constructor){ • Use typeof to test for string, number, B oolean if (typeof value == quot;stringquot;) {
  24. 24. Us e C ons tants function validate(value) { if (!value) { alert(quot;Invalid valuequot;); location.href = quot;/errors/invalid.phpquot;; } }
  25. 25. Us e C ons tants var Constants = { INVALID_MSG : quot;Invalid valuequot;, INVALID_URL : quot;/errors/invalid.phpquot; }; function validate(value) { if (!value) { alert(Constants.INVALID_MSG); location.href = Constants.INVALID_URL; } }
  26. 26. Us e C ons tants • R epeated unique values • UI strings • UR Ls • Any value that may change in the future
  27. 27. B uild Proces s M aintainable JavaS cript
  28. 28. B uild Proces s Source Files Build
  29. 29. R ecommendations • O ne object or object definition per file – Indicate dependencies • Use a build step – C ombine files in appropriate order – S trip comments/ whitespace – Validate code
  30. 30. S ummary M aintainable JavaS cript
  31. 31. S ummary • C ode C onventions • Loose C oupling • P rogramming P ractices • B uild P rocess
  32. 32. Ques tions and Ans wers M aintainable JavaS cript
  33. 33. E tcetera • M y email: nzakas@ yahoo-inc.com • M y blog: www.nczonline.net

×