Coding is like driving. Some road rules vary depending on where you are, but most are universal to keep drivers safe. A stop sign is a stop sign, regardless of where you are in the world.
Best coding practices are similar. While they may differ slightly from one language to another, these practices ensure code is easy to follow and understand. I think of this as clean code.
Here are a few guidelines that apply across languages. You can think of them as a roadmap to help you plan and write clean code.
- You know that frantic cleaning spree you go on right before your mom visits? You should never need to do that with your code before showing it to someone.
- Your code’s logic should be easy to follow. Declare all variables at the top before declaring functions and other processes.
- Variable names should usually hint at (or even explicitly state) the purpose they serve. For example, if you are writing code to track inventory at a grocery store, name a variable storing the number of beauty products in the warehouse “beautyProd” rather than “vegetables.”
- Don’t name a variable a key word in the language with which you’re working. For example, “select” should not be a variable name in SQL.
- Don’t start a variable name with numbers (Ex. “134beautyProd”).
- Don’t use special characters other than “_” to name a variable. “#&)5-6&*.+” is a terrible variable name.
- Every time you start a new chunk of code, include a line before it that describes its function.
- For example, if you are writing a “total” function to sum your inventory, write a line defining it as such. This ensures that someone else using or checking your code understands its purpose.
- The tab button is your friend. Use it when defining a function, writing a loop, or writing any type of nested statements.