CS 127: Data Structures
C++ Programming Style
Section 1.3 of your textbook has a really good overview of programming
style, which you should certainly consult. Here are some specific points
that I think are particularly important:
1. Line up braces. You'll find that the textbook tends to use method (a),
whereas I tend to use method (b). Either method is equally acceptable --
pick one and stick with it.
Method (a) |
Method (b) |
if (a == b)
{
c = d;
e = f;
} |
if (a == b) {
c = d;
e = f;
} |
2. Use whitespace in a meaningful way to make your code readable:
- Use tabs/spaces to indicate the level of nesting.
- Break up lines that are longer than 80 characters.
3. Use capitalization to make your identifiers clear:
- Variable and method names should start with a lower case letter.
Capital letters or underscores should be used to separate multiple words.
Examples:
name, age, personName, getAge, person_name, get_age
- Class names should start with a capital letter. Capital letters
or underscores should be used to separate multiple words. Examples:
class Person, class Gradebook, class BlackjackGame, class Blackjack_game
- Constants should be in all capital letters. Underscores should
be used to separate multiple words. Examples:
MAX_CAPACITY, DIME_VALUE
4. Keep your methods and functions short. A method/function shouldn't be
longer than 1-2 screens without good reasons.
5. All classes should be defined in a header file (.h), and implemented
in a code file (.cpp).
6. Each header file should contain header documentation containing:
- Programmer's name
- Date
- Assignment Number / Name
7. Each class header should contain documentation containing
- Name of class
- Description of purpose
- Known bugs
8. Each method and function should contain header documentation containing
- Name of method or function
- Description of purpose
- Description of parameters and return value
- Citations indicating ideas or code borrowed from other people /
sources