Intro to Computer Science II
Intro to Computer Science II CSCI 204
Popular in Course
Popular in ComputerScienence
This 20 page Class Notes was uploaded by Laurianne Mante on Saturday October 3, 2015. The Class Notes belongs to CSCI 204 at Bucknell University taught by Shane Markstrum in Fall. Since its upload, it has received 79 views. For similar materials see /class/218089/csci-204-bucknell-university in ComputerScienence at Bucknell University.
Reviews for Intro to Computer Science II
Report this Material
What is Karma?
Karma is the currency of StudySoup.
Date Created: 10/03/15
21 2 File Names Java Code Conventions Introduction Why Have Code Conventions Code conventions are important to programmers for a number of reasons 80 of the lifetime cost of a piece of software goes to maintenance Hardly any software is maintained for its whole life by the original author Code conventions improve the readability of the software allowing engineers to understand new code more quickly and thoroughly If you ship your source code as a product you need to make sure it is as well packaged and clean as any other product you create For the conventions to work every person writing software must conform to the code conventions Everyone Acknowledgments This document re ects the Java language coding standards presented in the Java Language Speci cation from Sun Microsystem S Inc Major contributions are from Peter King Patrick Naughton Mike DeMoney Jonni Kanerva Kathy Walrath and Scott Hommel This document is maintained by Scott Hommel Comments should be sent to shommelengsuncom File Names This section lists commonly used le suf xes and names File Suffixes Java Software uses the following le suf xes File Type Suffix Java source java Java bytecode class 3 File Organization 22 31 x Common File Names Frequently used le names include File Name Use GNUmakefile The preferred name for make les We use gnumake to build our software README The preferred name for the le that summarizes the contents of a particular directory File Organization A le consists of sections that should be separated by blank lines and an optional comment identifying each section Files longer than 2000 lines are cumbersome and should be avoided For an example of a Java program properly formatted see Java Source File Example on page 18 Java Source Files Each Java source le contains a single public class or interface When private classes and interfaces are associated with a public class you can put them in the same source le as the public class The public class should be the rst class or interface in the le Java source les have the following ordering Beginning comments see Beginning Comments on page 2 Package and Import statements Class and interface declarations see Class and Interface Declarations on page 3 Beginning Comments All source les should begin with a cstyle comment that lists the class name version information date and copyright notice Ciassname Version information Date Copyright notice Package and Import Statements 3 File Organization The rst noncomment line of most Java source les is a package statement After that import statements can follow For example package javaawt Class and Interface Declarations import javaawtpeerCanvasPeer The following table describes the parts of a class or interface declaration in the order that they should appear See Java Source File Example on page 18 for an example that includes comments Part of ClassInterface Declaration Notes i Classinterface documentation comment class or interface statement Classinterface implementation comment ifnecessary Class static variables Instance variables Constructors Methods See Documentation Comments on page 8 for information on what should be in this comment This comment should contain any classwide or interfacewide information that wasn t appropri ate for the classinterface documentation com m ent First the public class variables then the pro tected then package level no access modi er and then the private First public then protected then package level no access modi er and then private These methods should be grouped by functional ity rather than by scope or accessibility For example a private class method can e in between two public instance methods The goal is to make reading and understanding the code eas 1er 4 Indentation 41 42 Indentation Four spaces should be used as the unit of indentation The exact construction of the indentation spaces vs tabs is unspeci ed Tabs must be set exactly every 8 spaces not 4 Line Length Avoid lines longer than 80 characters since they re not handled well by many terminals and tools Note Examples for use in documentation should have a shorter line lengthigenerally no more than 70 characters Wrapping Lines When an expression will not t on a single line break it according to these general principles Break after a comma Break before an operator Prefer higherlevel breaks to lowerlevel breaks Align the new line with the beginning of the expression at the same level on the previous line If the above rules lead to confusing code or to code that s squished up against the right margin just indent 8 spaces instead Here are some examples of breaking method calls someMethodlongExpressionl longExpressionZ longExpression4 longExpressiOHS longExpressionB var someMethodllongExpressionl someMethodZlongExpression2 longExpression3 Following are two examples of breaking an arithmetic expression The rst is preferred since the break occurs outside the parenthesized expression which is at a higher level longNamel longNameZ longName3 longName4 7 longNameS 4 longname6 PREFER longNamel longNameZ longName3 longName4 7 longNameS 4 longname6 AVOID Following are two examples of indenting method declarations The rst is the conventional case The second would shift the second and third lines to the far right if it used conventional indentation so instead it indents only 8 spaces 5Commems CONVENTIONAL INDENTATION someMethodint anArg b ect anotherArg String yetAnotherArg bject andStillAnother INDENT 8 SPACES TO AVOID VERY DEEP INDENTS private static synchronized horkingLongMethodNameint anArg ject anot erAr String yetAnotherArg Object andStillAnother Line wrapping for if statements should generally use the 8space rule since conventional 4 space indentation makes seeing the body dif cult For example DON T USE THIS INDENTATION if conditionl ampamp conditionZ condition3 ampamp condition4 lcondition5 ampamp condition6 BAD WRAPS doSomethingAboutIt MAKE THIS LINE EASY TO MISS USE THIS INDENTATION INSTEAD if conditionl ampamp conditionZ condition3 ampamp condition4 1condition5 ampamp condition6 doSomethingAboutIt OR USE THIS if conditionl ampamp conditionZ ll lllcondition5 ampamp doSomethingAboutIt condition3 ampamp condition4 condition6 Here are three acceptable ways to format ternary expressions alpha aLongBooleanExpression beta gamma alpha aLongBooleanExpression beta gamma alpha aLongBooleanExpression gamma Comments Java programs can have two kinds of comments implementation comments and documentation comments Implementation comments are those found in C which are delimited by and Documentation comments known as doc comments are Javaonly and are delimited by Doc comments can be extracted to HTML les using the javadoc tool 5 Comments 51 Implementation comments are means for commenting out code or for comments about the particular implementation Doc comments are meant to describe the speci cation of the code from an implem entationfree perspective to be read by developers who might not necessarily have the source code at hand Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself Comments should contain only information that is relevant to reading and understanding the program For example information about how the corresponding package is built or in What directory it resides should not be included as a comment Discussion of nontrivial or nonobvious design decisions is appropriate but avoid duplicating information that is present in and clear from the code It is too easy for redundant comments to get out of date In general avoid any comments that are likely to get out of date as the code evolves Note The frequency of comments sometimes re ects poor quality of code When you feel compelled to add a comment consider rewriting the code to make it clearer Comments should not be enclosed in large boxes drawn with asterisks or other characters Comments should never include special characters such as formfeed and backspace Implementation Comment Formats Programs can have four styles of implementation comments block singleline trailing and endofline Block Comments Block comments are used to provide descriptions of les methods data structures and algorithms Block comments may be used at the beginning of each le and before each method They can also be used in other places such as Within methods Block comments inside a function or method should be indented to the same level as the code they describe A block comment should be preceded by a blank line to set it apart from the rest of the code Here is a block comment Block comments can start with which is recognized by indentl as the beginning of a block comment that should not be reformatted Example Here is a block comment with some very special formatting that I want indentl to ignore one two three 5Comments Note If you don t use indentl you don t have to use in your code or make any other concessions to the possibility that someone else might run indentl on your code See also Documentation Comments on page 8 SingleLine Comments Short comments can appear on a single line indented to the level of the code that follows If a comment can t be written in a single line it should follow the block comment format see section 511 A singleline comment should be preceded by a blank line Here s an example of a singleline comment in Java code if condition Handle the condition Trailing Comments Very short comments can appear on the same line as the code they describe but should be shifted far enough to separate them from the statements If more than one short comment appears in a chunk of code they should all be indented to the same tab setting Here s an example of a trailing comment in Java code if a 2 return TRUE else return isPrimea special case works only for odd a EndOfLine Comments The comment delimiter can comment out a complete line or only a partial line It shouldn t be used on consecutive multiple lines for text comments however it can be used in consecutive multiple lines for commenting out sections of code Examples of all three styles follow if foo gt 1 Do a doubleeflip else return false Explain why here 5 Comments 52 if bar gt 1 Do a tripleeflip el e return false Documentation Comments Note See Java Source File Example on page 18 for examples of the comment formats described here For further details see How to Write Doc Comments for Javadoc which includes information on the doc comment tags return param see httpjavasuncomproductsjdkjavadocwritingdoccommentshtml For further details about doc comments and javadoc see the javadoc home page at httpjavasuncomproductsjdkjavadoc Doc comments describe Java classes interfaces constructors methods and elds Each doc comment is set inside the comment delimiters with one comment per class interface or member This comment should appear just before the declaration The Example class provides public class Example Notice that toplevel classes and interfaces are not indented While their members are The rst line of doc comment for classes and interfaces is not indented subsequent doc comment lines each have 1 space of indentation to vertically align the asterisks Members including constructors have 4 spaces for the rst doc comment line and 5 spaces thereafter If you need to give information about a class interface variable or method that isn t appropriate for documentation use an implementation block comment see section 5 l l or singleline see section 512 comment immediately a er the declaration For example details about the implementation of a class should go in in such an implementation block comment following the class statement not in the class doc comment Doc comments should not be positioned inside a method or constructor de nition block because Java associates documentation comments with the rst declaration after the comment 6 62 63 6 Declarations Declarations Number Per Line One declaration per line is recommended since it encourages commenting In other words int level indentation int size size of tab level le is preferred over int level size Do not put different types on the same line Example int foo fooarrayll WRONGl Note The examples above use one space between the type and the identi er Another acceptable alternative is to use tabs eg int level indentation level ze size of table Object currentEntry currently selected table entry Initialization Try to initialize local variables Where they re declared The only reason not to initialize a variable Where it s declared is if the initial value depends on some computation occurring rst Placement Put declarations only at the beginning of blocks A block is any code surrounded by curly braces and Don t wait to declare variables until their rst use it can confuse the unwary programmer and hamper code portability Within the scope void myMethod intl 0 beginning of method block if condition int int2 0 beginning of quotifquot block The one exception to the rule is indexes of for loops which in Java can be declared in the for statement for int i 0 i lt maxLoops i 7 Statements Avoid local declarations that hide declarations at higher levels For example do not declare the same variable name in an inner block int count myMethod if condition int count AVOIDE 64 Class and Interface Declarations When coding Java classes and interfaces the following formatting rules should be followed No space between a method name and the parenthesis starting its parameter list Open brace appears at the end of the same line as the declaration statement Closing brace starts a line by itself indented to match its corresponding openin statement except when it is a null statement the should appear immediately after the a class Sample extends Object int iv int ivar2 Sampleint i int j iv arl i ivar2 j int emptyMethod Methods are separated by a blank line 7 Statements 71 Simple Statements Each line should contain at most one statement Example argv Correct argc Correct argv argcee AVOIDE 7 Statements 72 Compound Statements Compound statements are statements that contain lists of statements enclosed in braces statements See the following sections for examples The enclosed statements should be indented one more level than the compound statement The opening brace should be at the end of the line that begins the compound statement the closing brace should begin a line and be indented to the beginning of the compoun statem ent Braces are used around all statements even single statements when they are part of a control structure such as a if else or for statement This makes it easier to add statements without accidentally introducing bugs due to forgetting to add braces 73 return Statements A return statement with a value should not use parentheses unless they make the return value more obvious in some way Example return return myDisksize return size size defaultsize 74 if ifelse if elseif else Statements The if else class of statements should have the following form if condition statements if condition statements els e statements if condition statements else if condition statements else statements Note if statements always use braces Avoid the following errorprone form if condition AVOID1 THIS OMITS THE BRACES Hi statement 7 Statements 75 76 77 78 for Statements A for statement should have the following form for initialization statements condition update An empty for statement one in which all the work is done in the initialization condition and update clauses should have the following form for initialization condition update When using the comma operator in the initialization or update clause of a for statement avoid the complexity of using more than three variables If needed use separate statements before the for loop for the initialization clause or at the end of the loop for the update clause while Statements A while statement should have the following form while condition statements An empty while statement should have the following form while condition dowhile Statements A do while statement should have the following form do statements while condition switch Statements A switch statement should have the following form 8 White Space switch condition case AB statements falls through case DEF statements break case XYZ statements break default statements break Every time a case falls through doesn t include a break statement add a comment where the break statement would normally be This is shown in the preceding code example with the falls through comment Every switch statement should include a default case The break in the default case is redundant but it prevents a fallthrough error if later another case is ad e 79 trycatch Statements A try catch statement should have the following format tr statements catch EXceptionClass e statements A try catch statement may also be followed by finally which executes regardless of whether or not the try block has completed successfully try statements catch EXceptionClass e statements finally statements 8 White Space 81 Blank Lines Blank lines improve readability by setting off sections of code that are logically related 8 White Space 82 Two blank lines should always be used in the following circumstances Between sections of a source le Between class and interface de nitions One blank line should always be used in the following circumstances Between methods Between the local variables in a method and its rst statement Before a block see section 511 or singleline see section 512 comment Between logical sections inside a method to improve readability Blank Spaces Blank spaces should be used in the following circumstances A keyword followed by a parenthesis should be separated by a space Example while true Note that a blank space should not be used between a method name and its opening parenthesis This helps to distinguish keywords from method calls A blank space should appear after commas in argument lists All binary operators except should be separated from their operands by spaces Blank spaces should never separate unary operators such as unary minus increment Hr and decrement n from their operands Examp e a c d a a b C d while d s printsquotsize is quot foo quotnquot The expressions in a for statement should be separated by blank spaces Example for exprl expr2 exprw Casts should be followed by a blank space Examples myMethodbyte myMethodint aNum Cp Object x 5 int i 3 l Identifier Type 9 Naming Conventions Naming Conventions Naming conventions make programs more understandable by making them easier to read They can also give information about the function of the identi erifor example Whether it s a constant package or classiwhich can be helpful in understanding the code Rules for Naming Examples Package s Classes lnterfac es Methods The pre x of a unique package name is always written in alllowercase ASCII letters and should be one of the toplevel domain names currently com edu gov mil net org or one of the English twoletter codes identify ing countries as speci ed in ISO Standard 3166 1981 Subsequent components of the package name vary according to an organization s own inter nal naming conventions Such conventions might specify that certain directory name com ponents be division department project machine or login names Class names should be nouns in mixed case with the rst letter of each internal word capi talized Try to keep your class names simple and descriptive Use Whole wordsiavoid acronyms and abbreviations unless the abbre viation is much more Widely used than the long form such as URL or HTML Interface names should be capitalized like class names Methods should be verbs in mixed case with the rst letter lowercase with the rst letter of each internal word capitalized com sun eng comapplequicktimev2 educmucsbovikcheese class Raster class ImageSprite interface RasterDelegate interface Storing run i runFast getBackground 10 Programming Practices Identifier Type Rules for Naming Examples Variables Constants 10 10 10 h Except for variables all instance class and class constants are in mixed case with a lower case rst letter Internal words start with capi tal letters Variable names should not start with underscore 7 or dollar sign 39 characters even though both are allowed int char float i Ci myWidth Variable names should be short yet meaning f The c oice ofa variable name should be mnem onici that is designed to indicate to the casual observer the intent of its use Onechar acter variable names should be avoided except for temporary throwaway variables Com mon names for temporary variables are i j k m and n for integers c d and e for characters The names of variables declared class con stants and of ANSI constants should be all uppercase with words separated by under scores ANSI constants should be avoided for ease of debugging statlc flnal 11139 MINJ IIDTH p statlc flnal 11139 MAXJNIDTH static final int GETiTHEich H Programming Practices Providing Access to Instance and Class Variables Don t make any instance or class variable public without good reason Often instance variables don t need to be explicitly set or gotmnwften that happens as a side effect of method calls One example of appropriate public instance variables is the case where the class is essentially a data structure with no behavior In other words if you would have used a struct instead of a class if Java supported struct then it s appropriate to make the class s instance variables public Referring to Class Variables and Methods Avoid using an object to access a class static variable or method Use a class name instead For example c1assMethod OK ACIasscIassMethod OK 10 Programming Practices anObjectc1assMethod AVOIDl 103 Constants Numerical constants literals should not be coded directly except for l 0 and l which can appear in a for loop as counter values 104 Variable Assignments Avoid assigning several variables to the same value in a single statement It is hard to read Example fooBarfChar barFoolchar 39c39 AVOID1 Do not use the assignment operator in a place where it can be easily confused with the equality operator Example if c d AVOIDE Java disallows should be written as if c d ii 0 Do not use embedded assignments in an attempt to improve runtime performance This is the job of the compiler Example d a b c r AVOIDE should be written as b c a r LSD 9 en Miscellaneous Practices 70 5 7 Parentheses It is generally a good idea to use parentheses liberally in expressions involving mixed operators to avoid operator precedence problems Even if the operator precedence seems clear to you it might not be to othersiyou shouldn t assume that other programmers know precedence as well as you do 1 AVOIDE if a b ampamp c dgt USE 11 Code Examples 7052 7053 7054 11 111 Returning Values Try to make the structure of your program match the intent Example if booleanEXpression return true else return false should instead be written as return booleanEXpression Similarly if condition return x return y should be written as return condition x z y Expressions before 7 in the Conditional Operator If an expression containing a binary operator appears before the in the temary operator it should be parenthesized Example Special Comments Use XXX in a comment to ag something that is bogus but works Use FI XME to ag something that is bogus and broken Code Examples Java Source File Example The following example shows how to format a Java source le containing a single public class Interfaces are formatted similarly For more information see Class and Interface Declarations on page 3 and Documentation Comments on page 8 11 Code Examples Blahjava 182 990318 Copyright c 199471999 Sun Microsystems ln 901 San Antonio Road Palo Alto California c 94303 USA All Rights Reserved This software is the confidential and proprietary information of Sun Microsystems Inc quotConfidential Informationquot You shall disclose such Confidential Information and shall use it on accordance with the terms of the license agreement you entered into with Sun package javablah import javablahblahdyBlahBlah Class description goes here version 182 18 Mar 1999 author Firstname Lastname public class Blah extends SomeClass A class implementation comment can go here classVar1 documentation comment public static int classVar1 classVar2 documentation comment that happens to be more than one line long private static Object classVar2 instanceVar1 documentation comment public Object instanceVarl instanceVar2 documentation comment protected int instanceVar2 instanceVar3 documentation comment private Object instanceVar3 constructor Blah documentation comment public Blah implementation goes here public void doSomething implementation goes here method doSomething documentation comment 11 Code Examples method doSomethingElse documentation comment param someParam descrlptlon public void doSomethingElseObject someParam implementation goes here