Programming Style
Programming style refers to the approach a programmer takes when writing source code. The purpose of a good style is to make the code easy to read, understand, and maintain while reducing the chance of errors. Earlier styles often emphasized saving screen space, but modern practices focus more on clarity and structure.
A well-chosen coding style can compensate for the limitations of a programming language, while poor style can undermine even the most powerful language. The ultimate goal is to produce code that is clear, simple, and elegant. Programming styles are often influenced by organizational coding standards, established conventions, or the personal preferences of the programmer
General rules and guidelines for good programming style:
1. Clarity and Simplicity of Expression
Programs should be written so that their purpose is clear and easy to understand.
2. Naming
Modules, processes, variables, and other elements should be given meaningful names. Avoid cryptic or misleading identifiers.
Example:
a = 3.14 * r * r // unclear
area _of_ circle = 3.14 * radius * radius // clear and descriptive
3. Control Constructs
Use single-entry, single-exit control structures wherever possible to keep program flow simple and predictable.
4. Information Hiding
Data stored in structures should be hidden from the rest of the system whenever possible. This reduces coupling between modules and improves maintainability.
5. Nesting
Avoid deep nesting of loops and conditions. Excessive nesting makes code harder to understand and can lead to errors in logic.
6. User-Defined Types
Make effective use of data types such as class, struct, and union. These improve readability and make programs easier to write and maintain.
7. Module Size
Modules should be of uniform and reasonable size. Oversized modules often lack cohesion, while very small ones can create unnecessary overhead.
8. Module Interface
Keep module interfaces simple and clear. Complex interfaces should be carefully reviewed to prevent misuse.
9. Side Effects
Minimize or avoid side effects, such as modules altering program state unexpectedly. Such behavior can make debugging and maintenance difficult.