C++ Best practice and code profiling

Knowing the syntaxes, algorithm and programming logic doesn’t make me a good coder. Here are some webpages that I found useful for improving my codes:

Top 15+ Best Practices for Writing Super Readable Code

As of Oct 20, 2018, the 16 rules were:

  1. Commenting and documentation
  2. Consistent indentation (Read further on Wikipedia if you would like to learn the names of these styles)
  3. Avoid obvious comments (aka having reasonable function and variable names)
  4. Code grouping (for instance, initialising variables, reading files)
  5. Consistent naming scheme (camelCase vs underscores_between_words)
  6. Don’t Repeat Yourself (DRY; aka Duplication Is Evil -DIE)
  7. Avoid deep nesting (ideally you use recursive functions for nested for-loops; or use early return statements for nested if-statements)
  8. Limit line length (be kind to vim users – 80 characters maximum)
  9. File and folder organisation (depending on the actual application, inc/src/util/module could be a good starting point to build your source tree)
  10. Consistent temporary names (e.g. i , j for indexing)

  11. (for SQL) Capitalise SQL key words (SELECT id FROM database)
  12. Separate codes and data
  13. (for PHP) Alternate syntax inside templates (Read more here)
  14. Object-oriented vs Procedural (use classes whenever possible; procedures for independent tasks)
  15. Read codes in Open source projects (learn from other developers)
  16. Code refactoring (aka cleaning up the code which might involve rewriting it in a more readable structure without compromising its functionality)

This post on Medium / Hackernoon gives similar insights, with the following addition:

  1. Test coverage (write tests for each function and catch exceptions properly with informative error messages)
  2. Refactoring does not work (do not be tricked to believe that you will refactor your code at the end of the development. It is a heavy technology debt.)
  3. Don’t write code when you are tired or in a bad mood (2-5 times more bugs in codes)
  4. Don’t write all at once – make developing iterative
  5. Automation vs manual (automate right now if you have resources)

Recommended nomenclature on different platforms and some OOP tips can be found on this site.

Lastly, profiling your code can show you where the algorithms take the most time and where memory allocation could be improved. This article highlighted three tools, among which I prefer valgrind to most.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s