CS 10 Discussion Notes
18 April 2007
By Mock Suwannatat
18 April 2007
By Mock Suwannatat
Java Coding Style Guide
Source:
- http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html
- Conventional wisdom, past experiences
Indentation:
- Never use tabs. Use spaces instead.
- Use 2 or 4 spaces for each level of indentation (be consistent)
- No lines should be longer than 80 characters. If a line is long, break it up nicely.
- Always put { … } after an if-statement (recommended)
- Be consistent! Code with the same level must have the same level of indent.
Names:
- ClassName, variableName, methodName, CONSTANT_NAME
- Names should make sense. Don’t be shy for long names.
Variables:
- If an instance variable can be private, make it private. (almost aways)
- Declare instance variables at the top of your file.
- If it can be local, make it local.
- One declaration per line.
Methods:
- If a method can be private, make it private.
- Short methods are preferred.
- Should fit on a single screen. (no hard rule on this)
Comments:
- “Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself.”
- When commenting, stick with the 80-char rule.
- When a comment block is longer than 1 line, do not use //. Instead, use /* … */
- Trailing comments must be short, and far away from the code. Either /* … */ or // can be used for trailing comments.
- /** javadoc comments */ are for readers who may not see the code. Each public method/field should have a javadoc comment.
- // can be used for commenting out a block of code.
Tips on IDE & Tools:
- Free IDEs: Eclipse, NetBeans, BlueJ
- Free text editors: Crimson Editor (Windows), Smultron (Mac only)
- An IDE can help you indent better. It can also do other things.
- Auto-completion on variable names
- Matching ( parentheses ) and { brackets }
- Commenting/uncommenting code.
- Syntax coloring.
- Syntax checking!
- You still need to be able to use command line to compile and run your program.
Etc:
- One class per file (except for nested classes)
- …
- …
- …
1 comment:
This is great info to know.
Post a Comment