Rules for Coding Part One

The following rules are from the book Clean Code by Robert C Martin which I will cover over a few parts.

  1. Functions should be small. Each function should only be up to 4 – 5 lines of code
  2. If, else and while statements should be one line long, a function call. The function call should have a descriptive name. DO not hold nested structures, indent level shoould not be greater than 2.
  3. Functions should only do one thing. Make sure that all functions are at the same level of abstractions.
  4. Switch statements should be placed in a low level class and is never repeated. The best solution would be to bury the switch statement in the basement of an Abstract Factory
  5. Use descriptive names, long descriptive names that make it meaningful and says what the function does. Be consistent with names. Use the same phrases, nouns and verbs as the sequence tells a story.
  6. Arguments passed to a function should not exceed more than three, two is ideal. Having many arguments becomes complex when testing as you need to test every scenario.
  7. Flag arguments is terrible practise, passing a boolean to a function. It implies that the function does more than one thing. Break up the function into two, one for the true condition and one for the false condition.
  8. When a function takes in more the three arguments, one might consider creating a class of their own.
  9. Provide good names for functions explaining the intent for the function and the order and intent for the arguments
  10. Output arguments should be avoided. If the function must change the state of something, have it change the state of the owning object.
  11. Store arguments as instance variables and try not to pass through as arguments into a function.
  12. Functions should change the state of an object or return some information about an object. Doing both leads to confusion.
  13. Use exceptions instead of returning error codes. try/catch blocks are ugly and the contents of a try/catch bl;ock should be extracted into a function.
  14. Error handling is one thing, a function that handles errors should do nothing else. If a keyword try exists ina function, it should be the very first word and there should be nothing after the catch/finally blocks.
  15. When using exceptions rather than error codes, the new exception are derivatives of the exception class.
  16. Master programmers think of systems as stories to be told, rather than programs to be written.

Leave a Reply

Your email address will not be published.