Good Programming Style
Writing code that works is only half the job. Code must also be readable, maintainable, and well-organized. Good programming style makes your code easier to understand, debug, and modify — for yourself and for others.
Learning Objectives
- 11.5.3.12 Follow rules of good programming style
Conceptual Anchor
The Essay Analogy
Imagine reading an essay with no paragraphs, no punctuation, and random abbreviations. You'd struggle to understand it even if the ideas were brilliant. Code is the same — without proper formatting, naming, and comments, even correct code becomes unreadable. Good style is like good grammar: it communicates your intent clearly.
Rules & Theory
Rules of Good Programming Style
| Rule | Why It Matters | Example |
|---|---|---|
| Meaningful names | Variables/functions should describe their purpose | totalMarks not tm |
| Consistent indentation | Shows the structure of code (loops, conditions) | Use 2 or 4 spaces consistently |
| Comments | Explain WHY, not WHAT the code does | // Sentinel value to stop input |
| Use constants | Named constants instead of "magic numbers" | const int MAX_SIZE = 100; |
| Modularity | Break code into small, reusable functions | calculateAverage(marks, n) |
| Whitespace | Blank lines separate logical sections | Space between functions and sections |
| No global variables | Pass data through parameters instead | Prevents unintended side effects |
| Error handling | Anticipate and handle edge cases | Check for division by zero |
Bad vs Good Style
❌ Bad style:
int main(){int a,b,c;cin>>a>>b;c=a+b;if(c>100){cout<<"big";}else{cout<<"small";}return 0;}
✅ Good style:
#include <iostream>
using namespace std;
// Calculate and classify the sum of two numbers
int main() {
int firstNumber, secondNumber;
cout << "Enter first number: ";
cin >> firstNumber;
cout << "Enter second number: ";
cin >> secondNumber;
int sum = firstNumber + secondNumber;
// Classify the result
if (sum > 100) {
cout << "The sum is large." << endl;
} else {
cout << "The sum is small." << endl;
}
return 0;
}Naming Conventions
| Convention | Format | Used For |
|---|---|---|
| camelCase | totalMarks, firstName |
Variables, functions (C++, Java) |
| PascalCase | StudentRecord, LinkedList |
Classes, types |
| UPPER_SNAKE | MAX_SIZE, PI |
Constants |
| snake_case | total_marks |
Variables (Python, C) |
Comments: Quality Over Quantity
Don't comment obvious code like i = i + 1; // increment i. Instead, explain the
intent: // Move to next student record. Good comments answer
"Why?" not "What?".
Worked Examples
1 Refactoring: Magic Numbers → Constants
Before:
if (score >= 90) grade = 'A';
if (score >= 50) pass = true;
tax = salary * 0.13;After:
const int GRADE_A_THRESHOLD = 90;
const int PASS_MARK = 50;
const double TAX_RATE = 0.13;
if (score >= GRADE_A_THRESHOLD) grade = 'A';
if (score >= PASS_MARK) pass = true;
tax = salary * TAX_RATE;2 Modularity: Breaking Into Functions
// FUNCTION: Calculate average of an integer array
double calculateAverage(int arr[], int size) {
int total = 0;
for (int i = 0; i < size; i++) {
total += arr[i];
}
return static_cast<double>(total) / size;
}
// FUNCTION: Find maximum value in an array
int findMax(int arr[], int size) {
int maxVal = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > maxVal) {
maxVal = arr[i];
}
}
return maxVal;
}
int main() {
int marks[] = {78, 92, 65, 88, 71};
int n = 5;
cout << "Average: " << calculateAverage(marks, n) << endl;
cout << "Highest: " << findMax(marks, n) << endl;
return 0;
}Common Pitfalls
Single-letter Variable Names
Using a, b, x for everything makes code unreadable.
Exception: i, j, k are acceptable for loop counters.
Over-commenting
Comments that restate the code add clutter, not clarity.
count = count + 1; // add 1 to count is pointless. Explain why instead.
Inconsistent Style
Mixing camelCase and snake_case, or using 2 spaces in some places and 4 in others, makes code confusing. Pick one style and stick with it throughout the project.
Tasks
List five rules of good programming style.
Explain why using const int MAX = 100; is better than using the number 100
directly in your code.
Take this poorly-styled code and rewrite it following good programming practices:
int main(){int a[5]={1,2,3,4,5};int s=0;for(int i=0;i<5;i++)s+=a[i];cout<<s;}
Write a well-styled C++ program that reads student marks, calculates the average, and determines the grade. Use meaningful names, constants, comments, and at least one function.
Self-Check Quiz
Q1: Why should you use meaningful variable names?
Q2: What is a "magic number" and why should you avoid it?
Q3: What naming convention uses capitalFirstLetterOfEachWord?