CIS 110 Programming Style Guide
Programming style is one of the
holy wars of computer programming. However, regardless of your tastes one thing is certain:
when in Rome, do as the Romans do. That is, learning the accepted style of a programming language is just as important as learning the language itself.
Golden Rule
Be Consistent
E.g. always have 2 space tabs vs. 4 space tabs
Formatting
- Indent Code: Consistently following the "Golden Rule"
- General Format:
public class FooBar{
//Determines if param is equal to Peter
//params: String: name to be checked
//returns: boolean: whether the name is the same as Peter
public static boolean isPeter(String name){
return name.equals("Peter");
}
}
- Do not push braces to their own line:
public static void fooBar(int x){
System.out.println("THIS IS CORRECT");
}
NOT
public static void fooBar(int x)
{
System.out.println("THIS IS NOT CORRECT");
}
- Insert Spaces between mathematical operators and integers:
if(x < 10){
System.out.println("THIS IS CORRECT");
}
NOT
if(x<10){
System.out.println("THIS IS NOT CORRECT");
}
Comments
- Header Comment: Every file needs a header comment with the name and assignment
// Ada Lovelace, ada@lovelace.com
// CIS 110 (section 005) - Homework 1
// [One-to-two sentence description of what the program does]
- Method Comment: Every method needs a comment (placed ABOVE the method) to briefly describe what the method does, what it takes as parameters, and what it returns. The following is an example of one possible comment layout, but any layout is fine as long as it covers all of the information listed above:
//Adds the params
//params: int: to be added, double: to be added
//returns: double: the result of the two numbers being added
public static double addNumbers(int x, double y){
return x + y;
}
if the method takes no parameters and/or the method does not return a value then a short description will do:
//Prints Hello
public static void printsHello(){
System.out.println("Hello");
}
- In-Line Comments: Use these comments only if a code fragment is extremely confusing. This should only be used rarely.
//Confusing method
public static void confusingMethod(){
System.out.println("B"); //where B is a grade
}
Naming
- Capitalization: Capitalize constants/final variables "LIKE_THIS", locals and fields "likeThis", method names "likeThis", and class names "LikeThis".
- Choosing Names:
- Use descriptive, concise names unless the value is a temporary or a loop variable (e.g., i, j...)
- Locals, fields, and constants should be nouns; method names should be verbs
Design
- Main Method: The Main Method should be a concise summary of your program, i.e., it should not contain any actual "work" such as println statements.
- Other Methods: Create methods that are short and capture the essence of the problem at hand, e.g., if a problem contains sub-problems, then a method that solves that problem should contain calls to other methods that solve the sub-problems.