Advertisement
Guest User

06.Използване на конструкции за управление - условни изрази

a guest
Jan 7th, 2016
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.27 KB | None | 0 0
  1. Използване на конструкции за управление – условни изрази и цикли
  2. The most important to consider when organizing code is ordering dependencies
  3. Wrong:
  4. GetData();
  5. GroupData();
  6. Print();
  7.  
  8. Correct:
  9. data = GetData();
  10. groupedData = GroupData(data);
  11. PrintGroupedData(groupedData);
  12.  
  13. Always put the normal (expected) condition first after the if clause
  14. Wrong:
  15. var response = GetHttpWebResponse();
  16. if (response.Code == Code.NotFound)
  17. {
  18. // ...
  19. }
  20. else
  21. {
  22. if (response.Code == Code.OK)
  23. {
  24. // ...
  25. }
  26. }
  27.  
  28. Correct:
  29. var response = GetHttpWebResponse();
  30. if (response.Code == Code.OK)
  31. {
  32. // ...
  33. }
  34. else
  35. {
  36. if (response.Code == Code.NotFound)
  37. {
  38. // ...
  39. }
  40. }
  41.  
  42. Avoid comparing to true or false
  43. Wrong:
  44. if (HasErrors == true)
  45. {
  46. ...
  47. }
  48. Correct:
  49. if (HasErrors)
  50. {
  51. ...
  52. }
  53. Start from the most common cases and then go to the more uncommon ones
  54.  
  55. Avoid double negation:
  56. Wrong:
  57. if (!HasNoError)
  58. {
  59. DoSomething();
  60. }
  61. Correct:
  62. if (HasErrors)
  63. {
  64. DoSometing();
  65. }
  66.  
  67. Do not use complex if conditions
  68.  You can always simplify them by introducing boolean variables or boolean methods
  69. Wrong:
  70. if (x > 0 && y > 0 && x < Width-1 && y < Height-1 &&
  71. matrix[x, y] == 0 && matrix[x-1, y] == 0 &&
  72. matrix[x+1, y] == 0 && matrix[x, y-1] == 0 &&
  73. matrix[x, y+1] == 0 && !visited[x, y])
  74. the code above can be refactored in this way:
  75. bool inRange = x > 0 && y > 0 && x < Width-1 && y < Height-1;
  76. if (inRange)
  77. {
  78. bool emptyCellAndNeighbours =
  79. matrix[x, y] == 0 && matrix[x-1, y] == 0 &&
  80. matrix[x+1, y] == 0 && matrix[x, y-1] == 0 &&
  81. matrix[x, y+1] == 0;
  82. if (emptyCellAndNeighbours && !visited[x, y]) …
  83. }
  84.  
  85. Write numeric boolean expressions as they are presented on a number line:
  86.  
  87.  
  88. -------|---------|------------|---------
  89. a x b
  90. correct:
  91. if(a < x && x < b) { … }
  92.  
  93. for loops
  94. - Use meaningful variable names
  95. Correct:
  96. for (int year =2000; year < 2015; year++) { … }
  97.  
  98. Avoid code that depends on the loop’s last index
  99.  
  100. Добре е циклите да са кратки. За да бъдат кратки е добре да отделяме по-големите парчета код в отделни методи
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement