Programming Best Practices - practical tips
Programming Best Practices for any language like:
- JavaScript
- Java
- Python
- Ruby
- CSS
- PHP
- C++
- C
The idea is to collect as much as possible best practices for programming and developing.
In this post:
- Programming language differences
- Variable names conventions
- Comments
- Code format
- indentation
- line length
- grouping code lines
- Project organization
- Use snippets
- Use complexity
- Principles
- DRY
- Resources
Programming language differences
When in doubt keep to your language best practices. Some languages like Python are designed and expect programmers to write compact, explicit and beautiful code. On the other hand languages like Java are verbose and provide a lot of information for the programmer.
This means that some practices could be controversial depending on the language and the framework. In case of controversial or confusing tip it would be shown as additional note(in this point):
For example if you have variables in Java and Python you could have the following situation(this just an example showing some difference in programming languages) :
FirefoxDriver fb = new FirefoxDriver();
ChromeDriver fb = new ChromeDriver();
WebDriver wb = new FirefoxDriver();
vs
driver = webdriver.Firefox()
As you can see you can find some extra information in the Java - type declaration. You have a type which provides what is the author indentation and what is supposed to be done with this variable. While in python you may need to add this kind of information in the variable name since you don't have type declaration.
In other words you have:
FirefoxDriver fb vs driver
Variable names conventions
Of course in any case your variable names should be descriptive and self explaining. Another programmer should be able to easily read and understand your code. Even you may have problems with your own code if you return back to it after months of years. That's why variable names are very important.
Your current project convention could contradict to the official ones. Some examples per language for variables:
- displayName (C#)
- displayName (Java)
- display_name (Python)
- display-name (Lisp)
functions/methods:
- MyMethodName (C#)
- myMethodName (Java)
- my_method_name (Python)
For Java only(depending on the programming element):
- UpperCamelCase - classes
- lowerCamelCase - class members, local variables
- org.acme.project.subsystem - packages
- ALL_CAPS - constants
For python we can find in the official guide PEP 8:
Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.
For popular languages the naming of variables is flexible and you have freedom. You can stick to some basic rules:
Variable names rules
- Variable names should be short and descriptive
- Variable names should follow the language convention
- Variable names consists from letters, numbers, and underscore (_)
- Do not mixed styles in project(avoid using user_name, userName, UserName etc in one project)
- Create naming/convention guide for new programmers
- Before working on new project/language check what are the variable names rules
Comments
Use comments even if your code is simple or readable. Comments will help any person reading your code to understand your logic and purpose. Of course you don't need to comment obvious statements like:
# prints text Hello, World! to console
print('Hello, World!')
Instead try to explain what is the purpose of this code:
Example of hello world program in python
You need to be familiar with your language comment style and guideline. Is your language supporting single and multi line comments? Can you automate comments with your IDE (IntelliJ, PyCharm)? Do you have a way of reviewing documentation of methods, classes?
Comments rules
- Avoid stupid comments
- useless comment
- stupid code, they force me do it
- Describe functionality and code purpose
- Be short and explicit
- Check your language comment guideline
- Search for commenting tools like javadoc
- Add parameters and return type for functions
- Don't mixed comment styles
- Comments can be done above the line or on the same line
Code format
In this section you can find several different topics like:
- indentation
- line length
- grouping code lines
indentation
You can have difference between language, operating system, project, IDE and programmers. The big dilemma here is: 4 spaces vs 1 tab. All this depends on the coding style of your project. Personally I prefer tabs instead of spaces because they are easier to be added or deleted. Several advices here:
- avoid mixing spaces and tabs
- customize your IDE to use only tabs or spaces
for x in range(3):
print("4 spaces")
print("1 Tab")
line length
The length of your code lines is another important feature of your code. If you use too long lines then people with smaller displays(laptops) may have problems reading your code. On the other hand to small code lines are really annoying and can be pain for the programmer(for example with HTML). You can try to find the optimal length and inform all guys in your project to keep to this recommended length.
- define a maximum length limit
- set a optimal line limit
- wrapping long lines/break over multiple lines
Python wrapping with backslashes
with open('/path/to/some/file/you/want/to/read') as file_1, \
open('/path/to/some/file/being/written', 'w') as file_2:
file_2.write(file_1.read())
grouping code lines
You can make group of code lines in your code in order to separate logic and adding a comment to each group. Grouping will make it easier for all other people who need to review, analyze and maintain your code. Be a nice guys and try to organize your code in logic units:
# read file
path = '/user/file.txt'
my_file = open(path,'r')
my_data = my_file.read()
# write file
new_path = '/user/new_file.txt'
new_file = open(new_path,'w')
new_file.write('sample text')
print(title)
Project organization
Most frameworks has well defined structure which separates:
- configuration files
- source code
- data
- DB
- business layer
- front end
Avoid using 'flat' file organization - putting all files in a single folder. Don't use versioning of your files like:
- fibon.py
- fibon1.py
- fibon2.py
This could be really confusing and someone can spend hours of trying to find what is the difference between these files and what is the last version ( to be honest I'm also doing this mistake due to laziness or trying to save time..)
Use snippets
Prepare snippets for repetitive pieces of code. This will save you time and decrease the make your code easier to be maintained. Place all snippets on a place with easy access for all your colleagues.
The other benefit of using code snippets is - with these tiny code parts you will be able to have code standards. This is even a requirement in some organizations.
count = 0
while count < 10:
print('Step: ' + str(count))
count = count + 1
Avoid complexity
Try to avoid complexity of your code and logic. Of course it's nice and fancy to have a solution which is working but no one understands it. But imagine that one day you may need to change the logic or fix a tiny bug.
Once I was a witness of such a case. A programmer solved trivial problem by extremely complex solution - nesting several recursions. He was really proud of his solution and even promoted because of it's creativity. But several months later he had to find a tricky problem. Wasted days of debugging, anxiety and one lesson learned
Principles
DRY
Famous DRY (Don't Repeat Yourself) principle is originated in book The Pragmatic Programmer by Andy Hunt and Dave Thomas. The idea behind is to avoid repetition of your code.
instead of
print('Step: 1')
print('Step: 2')
print('Step: 3')
use:
for count in range(3):
print('Step: ' + str(count))