Practice writing clean and simple code

I remember the 1st year school days in SUST when I started writing code in pascal. A simple prime number generation program lasted in 100 lines script :), I added and I commented off, and finally when the script is ready, I used to find 70% code that are commented off. That was a time when time flew so fast. Night after night we woke to solve problems. From the 2nd year I started to be a beat clean and precise in writing code. Got rid of redundant code, tried to make the code readable, used functions wherever appropriate.
Writing clean code is a major requirement in a professional environment where we are working in a team. We have to make sure, anyone can read our code. It is the code that stays, the coder may change everyday. If the code is not clean enough to be read by the a new coder, it is useless. Following are some general practices I would like to mention:

  1. Give the variables some long and meaningful name that have longer scope in the script. Do not name like a, b, c, ab, zx etc. The variable created at line 5 of the script cannot be remembered at line 150 unless it has a proper name. Use short names of 1 or 2 characters only when you are sure that the scope of this variable is short. For example in an independent for loop.
  2. Indent the code properly. After any first braces ({), whether it is if statement or for loop or while loop , give an indent of 2 spaces. Make the reader understand where the block starts and ends.
  3. Make the lines shorter horizontally, so that a reader can read the code without scrolling horizontally. For example, if we have a large if condition like this:

    if(total > 0 && subtotal > 0 && (total != subtotal || shipping > 0 || gv_discount > 0) && products_count > 0 )

    , we can write it like this,

    if(total > 0 && subtotal > 0 && 
      (total != subtotal || shipping > 0 || gv_discount > 0) && 
       products_count > 0 )

    This way the code becomes more readable.

  4. Split the system into independent modules so that no single script has hundreds of lines of code.
  5. Although code commenting is said to be a good practice in regard of code’s readability, I would prefer not to have many comments; rather have a clean code with proper naming. The code itself should be self-documented, otherwise we are not there yet. If a new coder looks at our code and cannot understand our intent, then either of us have some problem. We should very carefully avoid unnecessary complexity in the logic. Smart coder writes the simplest code possible to solve the most complex problem. It is the dumb coder who writes complex code to solve simple problems.

These are the very basic conventions I think should be practiced in professional environment. If you have any other opinion feel free to put some comments.

  1. No comments yet.
(will not be published)

  1. seo