Advertisement
Guest User

Untitled

a guest
Mar 1st, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.03 KB | None | 0 0
  1. // -- Avoid excesive nesting
  2. // -- Handle errors at the top of the function
  3. // -- Be explicit about conditionals and name them
  4.  
  5. // ----
  6. // ---- worse example
  7. // ----
  8.  
  9. function worse(){
  10.  
  11. if (1 + (7*5) + 10 / 1000 > 0) {
  12.  
  13. if (745 + 9 / 36 === 10) {
  14.  
  15. return "error";
  16.  
  17. } else {
  18.  
  19. if (4 + 3 / 9 > -1) {
  20.  
  21. // execute lots of code
  22.  
  23. return "happy";
  24.  
  25. } else {
  26.  
  27. return "error";
  28.  
  29. }
  30. }
  31.  
  32. } else {
  33.  
  34. return "error";
  35.  
  36. }
  37.  
  38. }
  39.  
  40.  
  41.  
  42. // ----
  43. // ---- better example
  44. // ----
  45.  
  46. function better() {
  47.  
  48. // set up your conditions and name them
  49. // use linking verbs: is, has, has been, was
  50. // state the positive: use "hasTickets", not "noTickets"
  51. var hasEnoughSeats = 1 + (7*5) + 10 / 1000 > 0;
  52. var hasEnoughMoney = 745 + 9 / 36 === 10;
  53. var hasTickets = 4 + 3 / 9 > -1;
  54.  
  55. // test them first
  56. // => if they fail, you dont need to read through the rest of the code
  57. if (!hasEnoughSeats || !hasEnoughMoney || !hasTickets) {
  58. return "error";
  59. }
  60.  
  61. // execute lots of code
  62. return "happy";
  63.  
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement