Version 41
This document gives some rules of thumb for writing programs in good style. No set of rules can cover all possible situations; use common sense always. The purpose of good style is to make programs easily readable and intelligible. This has at least two important benefits: it helps us avoid errors when writing the program initially, and we or others who subsequently need to revise the program won't be confused.
Standards are listed under the chapter where they first become applicable.
Put all import statements at the top of the file, before any function definitions or other code (but below the header comment, if there is one).
Use white space to make code clearer:
+ and =
z=3*x+5.2*yz = 3 * x + 5.2 * yIdentifiers (such as variable, function, and module names) should be meaningful and (even more importantly) not misleading. This applies to function parameters as well as other variables.
Good:
student_name = "Jack"
Bad, meaningless:
n = "Jack"
Worse, misleading:
score = "Jack"
However, in some contexts it is okay to use short, standard variable names, like i and j for indexes or counters in a loop, and n for a generic integer (in a purely mathematical function).
For long identifiers, use underscores or capitalization to separate the parts, e.g., best_of_three or bestOfThree.
Where Python requires code to be indented (function bodies, for statements, etc.), use two to four spaces for each level of indentation. Be consistent: don't use two spaces for one block of code and four for another. Do not use TAB characters to indent (but you may use the Tab key if your editor converts it to spaces).
Lines should be no more than 79 characters wide. Longer lines will "wrap around" when printed, making them ugly and hard to read. Split complex statements across lines at sensible breaking points, using \ if needed, and indent the continuation lines.
Avoid redundant tests in if statements. For example,
if score > 85:
return "Good"
elif score > 50:
return "So-so"
else:
return "Poor"
is preferable to
if score > 85:
return "Good"
elif score > 50 and score <= 85:
return "So-so"
elif score <= 50:
return "Poor"If an if statement has one or more elif clauses, it should end with an else clause to make it sure and clear that all cases have been covered. The else clause might print an error message for an unexpected value.
Use boolean variables and expressions outside the context of an if statement to simplify code. For example,
return x == y
is preferable to
if x == y
return True
else
return FalseUsually, True and False should be used in boolean context rather than 1 and 0 or other values.
Each source file should begin with a header comment which shows the course number, lab number, author's name(s), and date, in this form:
# INFO I210, Lab 3
# (Your name)
# (Today's date)Use comments to identify and briefly describe each problem, e.g.,
# Page 205, Exercise 6.10
# Display an animated, dancing skeletonCorrect spelling in comments and code makes the program easier to read and understand.
Code should be clear, simple, and straightforward to the extent possible. Avoid obscure and bizarre usages and unnecessary complexity.
Code that is not self-explanatory should be documented with comments.
Use spaces to separate the parts of expressions and lists. For example (I am using _ to represent a space more visibly), 5 * (x + 1) is better than 5*(x+1).
But, do not use spaces to separate parentheses from what they contain. Write (x_+_1), not (_x_+_1_). Likewise, do not space between a list, string, dictionary, or tuple and its subscript. For example, write scholar[i], not scholar [i]. Spacing is not required around the : in a slice operation: myString[2:8] is fine.
Use parentheses if they will help to clarify complex expressions.
If a function is getting too complex, divide it into subproblems, and define a helping function for each of the subproblems. Generally, several short functions are better than a single long function.
Use functions to avoid code repetition. It is hard to give strict rules about this, but here are some rules of thumb:
Use functions to improve code clarity. Sometimes the meaning of a few lines, or even one line, of code can be made clearer by wrapping it in a function definition and giving it a name. This may be true even if the lines are unrepeated.
Write a comment above each function (a "header comment") that explains what its parameters are, what it does, what value it returns, unless this information is perfectly obvious from reading the function's name, return type, and parameter list. The header comment should also explain what conditions must be true before the function is called (preconditions), and what conditions the function guarantees to be true when it returns (postconditions).
Avoid using the same name for a local variable and an instance variable (shadowing).
In general, rules for style concerning functions apply also to methods.
Use character-case to distinguish between the names of classes, functions, variables, and constants:
Use "camel case" for class names: begin with a capital letter, and capitalize "word parts" within the name.
Examples: Point, GeometricObject, SolarSystem
Begin variable and function names (this applies also to instance variables and and methods) with a lower-case letter. Either separate "word parts" with underscores, or capitalize following "word parts"; but do it the same way consistently within a program.
bear, bear_facts, live_a_littlebear, bearFacts, liveALittleUse all-upper-case identifiers for constants. Separate word parts with underscores.
PI, FISH_SHAPEModule names should be all lower-case, with word parts separated by underscores.
Examples: point, geometric_object, solar_system
Design of class hierarchies:
Let each class manage its own data, using constructors, accessors, and mutators.
Use other object-oriented design techniques (in addition to inheritance) to avoid redundancy:
Delegation: an object performs a task by asking another object to perform the task.
Polymorphism: different classes can define methods with the same name that behave differently. For example, different shapes draw themselves in different ways.