CPSC120A
Fundamentals of Computer Science I

Code Conventions

Coding style guidlines.

General

  1. Programming Practices

    1. Avoid magic numbers (literal primitive numbers) and magic strings by using variables with meaningful names.

    2. Write functions that are small and do one thing.

    3. Write test cases before writing any code.

  2. Formatting

    1. All lines should be less than 80 characters (the default width of an Emacs window). The best way to ensure that all lines of code are less than 80 characters is to write simple statements that do only one thing. When a line must span multiple lines:

      • break after commas.

      • break before operators.

      • prefer higher level breaks.

    2. Functions should be 40 lines or less, including comments.

    3. Indent with spaces (the default behavior for Emacs), not with tabs.

  3. Documentation

    1. Files should have a block comment at the top with the author
    1. All functions should have a block comment above them that includes:

      • The pre and post conditions of the function. If the pre conditions are met before execution, then the post conditions are guaranteed to be true on completion. The precondition must document every parameter and any instance variables used in the function. The postcondition should document all variables that may change during execution and the return value.
  1. Statements

    1. Lines should not have more than one statement.

    2. Use only one assignment operator per statement.

    1. Create flat programs, i.e. avoid nesting conditionals, functions, and loops multiple times.
  2. White Space

    1. Blank lines should be used to separate related sections of code and should be preceded by a comment explaining the section of code.
    1. Binary operators (+, -, *, etc.) should be separated from their operands by spaces (except for the . operator).

    2. Unary operators (-, ++, etc.) should not be separated from their operand by a space.

    3. Argument lists should have spaces after commas.

  3. Naming Conventions

    1. Names for variables, functions, and classes should be meaningful. Common abbreviations are OK (avg, max, etc.) but single character names and acronyms should be avoided.

    2. Function names should start with verbs and describe what the function does.

Python

  1. Programming Practices

    1. Default parameters and named arguments break the spaces around binary operator rule.

    2. Do not use from module_name import . Instead replace the with what specifically to import from the module.