When writing code in any language, there are good coding practices and there are really bad ones. Both may be correct as far as compiling and when run, but bad code can present some problems in development, debugging, and modifying. No matter how well your program runs, someone will have to read and/or alter your code at some point. They may have to add new features, correct a rare bug, or just want to read it to understand how it works. Similarly, you will have to read someone else's code to do the same thing.
Difference between good code and bad code lies in, at least, two major aspects: style and intent. The word "style" here not in its traditional meaning, as in fashion, but as a programming style, which can be bad, OK and great. Where, "intent" is an aspect, closely related to style. However, the main point here is not elegance, but readability. Good code requires minimum efforts from a reader to understand the author's intent. As per machine aspect good code take less resource and less time to process a task than a bad code. In good code, the parts are each individually of high quality, and also fit together seamlessly and runs smoothly. In case of bad code, the individual parts are shoddy, and they're jammed together in a way that makes no sense, which cause it to runs rough, and not for long.
Qualities of a good code -
- Easy to understand.
- Good code is well-organized.Data and operations in classes fit together.There aren't extraneous dependenciesbetween classes.
- Considers the by products that are not explicit - like security, compile time, smaller operations, number of calls, etc.
- Runs in reasonable time.
- Comments explain why things are done not what is done.The code itself explains what is done.The need for comments should be minimal.
- Uses meaningful naming conventions for all but the most transient of objects.
- Code should be well-tested.Tests serve as an executable specification of the code and examples of its use.
Qualities of a bad code -
- Bad code looks like something which was put in a hurry without giving any semblance of thought.
- No documentation.
- Unnecessarily use of loops and jumps statements.
- Take lot of times and resource to execute than usual.
- Poor coding standard and style.
- Complex and not straight forward.
- Poorly tested and fails silently.
How do you know you're writing good code?
When you have to go back and add/modify a feature, is it difficult?Do you constantly break existing functionality when making changes? If the answer to the above is "yes" then you probably have a poor overall design. It is a bit difficult to judge a design until it is required to respond to change.