Tips to avoid Crappy Code and write Clean Code for Programmers and Software Engineer

By ridhigrg |Email | May 21, 2019 | 5583 Views

Let's keep up everything in brief: If a C++ class definition takes up more than 1,000 lines, it's a pretty good indication that the class has multiple responsibilities and needs to be broken up. If a C++ function is more than a couple of screenfuls, it's a pretty good indication that it needs to be broken up. A function with more than half a dozen arguments is way too complex, and be suspicious if it needs a strict argument. A template with more than three parameters is too complex, and be suspicious if it needs a traits class.

  • Keeping it brief doesn't apply to comments. Write down everything. Some people say the code should document itself. This is wrong. Programming languages are great for describing the implementation but horrible for describing intent. Natural language comments are for intent.

  • If you have more than three levels of indentation, you are drowning in the if/else logic. You need to step back and look for places where you can simplify the termination condition. You need to see if making part of the logic its own function would simplify the flow of control.

  • Test every return value. If you don't, your program will eventually crash mysteriously, and you'll never figure out why. Those return codes are telling you why.

  • The difference between a prototype and a finished piece of code is error handling, test cases, and reconfigurability. That stuff should about double the size of your code. If it doesn't, you aren't done yet.

  • Well-formatted code is easy-to-read code. Indentation, spacing, and comments matter way more than you might think to readability. Slow down and get it right. You'll be back this way in two years, and you want to remember what you did.

  • Don't call exit(), abort() or similar functions without first printing a message saying why you aborted the program. A program that stops without saying anything is pretty mysterious and hard to debug.

  • Be wary of virtual functions and function pointers. Be afraid of multiple inheritances. Run screaming from virtual multiple inheritances. These are the path to madness.

Source: HOB