[Java Coding Conventions Why ? 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. Remember that code is read much more than it is written. Java Source Files Each Java source file 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 file as the public class. The public class should be the first class or interface in the file. Java file structure: BR || '||<:> 'Part of Class\Interface||<:> Notes || ||.1||<:> Package Name|||| ||.2||<:> Imported packages|||| ||.3||<:> Class/interface documentation comment||See documentation section|| ||.4||<:> class or interface statement||e.g public class AAA extends BBB|| ||.5||<:> Class/interface implementation comment|||| ||.6||<:> Class (static) variables||First public, then protected, then package level (no access modifier), and then private.|| ||.7||<:> Instance variables||First public, then protected, then package level (no access modifier), and then private.|| ||.8||<:> Constructors|||| ||.9||<:> Methods||These methods should be grouped by functionality rather than by scope or accessibility. For example, a private class method can be in between two public instance methods. The goal is to make reading and understanding the code easier.|| Line Length Avoid lines longer than 80 characters, since they're not handled well by many terminals and tools. Wrapping Lines When an expression will not fit on a single line, break it according to these general principles: * Break after a comma. * Break before an operator. * Prefer higher-level breaks to lower-level 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. Comments * There are two kinds of comments: a) Implementation comments are delimited by /*...*/ and are for describing the implementation. b) Documentation comments (known as "doc comments") are delimited by /**...*/. describe the specification of the code. Doc comments can be extracted to HTML files using the javadoc tool. * Make code self documenting before commenting it. * Comments should be used to give overviews of code and provide additional information that is not readily available in the code itself. * Avoid any comments that are likely to get out of date as the code evolves. Block Comments For files, methods, data structures and algorithms description. {{{ /* * Here is a block comment. */ }}} Single-Line Comments Short comments (preceded by a blank line). {{{ if (condition) { /* Handle the condition. */ ... } }}} End-Of-Line Comments Commenting out sections of code or till the end of the line (only line). {{{ if (foo > 1) { // Do a double-flip. ... } else { return false; // Explain why here. } //if (bar > 1) { // // // Do a triple-flip. // ... //} //else { // return false; //} }}} Documentation Comments See JavaDoc Conventions BR Declarations * One declaration per line: {{{ int level; // indentation level int size; // size of table }}} * Try to initialize local variables where they're declared. * Put declarations only at the beginning of blocks: {{{ void myMethod() { int int1 = 0; // beginning of method block if (condition) { int int2 = 0; // beginning of "if" block ... } } }}} * Avoid local declarations that hide declarations at higher levels. (same variable name in an inner block). 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 opening statement, except when it is a null statement the "}" should appear immediately after the "{". {{{ class Sample extends Object { int ivar1; int ivar2; Sample(int i, int j) { ivar1 = i; ivar2 = j; } int emptyMethod() {} ... } }}} * Methods are separated by a blank line. Statements Simple Statements Each line should contain at most one statement. Example: {{{ argv++; // Correct argc--; // Correct argv++; argc--; // AVOID! }}} 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 compound statement. * 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. 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 myDisk.size(); return (size ? size : defaultSize); }}} if, if-else, if else-if else Statements {{{ if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition) { statements; } else if (condition) { statements; } else { statements; } }}} Note: if statements always use braces {}. Avoid the following error-prone form: {{{ if (condition) //AVOID! THIS OMITS THE BRACES {}! statement; }}} Perfer positive condtions: {{{ //Prefer if (a == 1) { … } else { … } //Avoid if (a != 1) { … } else { … } }}} Unless there is no else. for Statements {{{ for (initialization; condition; update) { statements; } }}} 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 {{{ while (condition) { statements; } }}} An empty while statement should have the following form: {{{ while (condition); }}} do-while Statements {{{ do { statements; } while (condition); }}} switch Statements {{{ switch (condition) { case ABC: 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 fall-through error if later another case is added. try-catch Statements {{{ try { statements; } catch (ExceptionClass e) { statements; } }}} ... with finally {{{ try { statements; } catch (ExceptionClass e) { statements; } finally { statements; } }}} 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 ("++"), and decrement ("--") from their operands. Example: {{{ a += c + d; a = (a + b) / (c * d); while (d++ = s++) { n++; } printSize("size is " + foo + "\n"); }}} The expressions in a for statement should be separated by blank spaces. Example: {{{ for (expr1; expr2; expr3) }}} Casts should be followed by a blank space. Examples: {{{ myMethod((byte) aNum, (Object) x); myMethod((int) (cp + 5), ((int) (i + 3)) + 1); }}} Naming Conventions BR See Naming Conventions General 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 gotten-often 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: classMethod(); //OK AClass.classMethod(); //OK anObject.classMethod(); //AVOID! Constants Numerical constants (literals) should not be coded directly, except for -1, 0, and 1, which can appear in a for loop as counter values. Variable Assignments Avoid assigning several variables to the same value in a single statement. It is hard to read. Example: {{{ fooBar.fChar = barFoo.lchar = 'c'; // AVOID! }}} Do not use the assignment operator in a place where it can be easily confused with the equality operator. Example: {{{ if (c++ = d++) { // AVOID! (Java disallows) ... } }}} should be written as {{{ if ((c++ = d++) != 0) { ... } }}} Do not use embedded assignments in an attempt to improve run-time performance. This is the job of the compiler. Example: {{{ d = (a = b + c) + r; // AVOID! }}} should be written as {{{ a = b + c; d = a + r; }}} 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 others-you shouldn't assume that other programmers know precedence as well as you do. {{{ if (a == b && c == d) // AVOID! if ((a == b) && (c == d)) // RIGHT }}} 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 : y); }}} Expressions before `?' in the Conditional Operator If an expression containing a binary operator appears before the ? in the ternary ?: operator, it should be parenthesized. Example: {{{ (x >= 0) ? x : -x; }}} Special Comments Use XXX in a comment to flag something that is bogus but works. Use FIXME to flag something that is bogus and broken. For each class you create, include JUnit tests for that class See UnitTesting Conventions Follow a “canonical form” When creating a class for general-purpose use. Include definitions for equals( ), hashCode( ), toString( ) ,Implement Comparable and Serializable if required. Whenever reasonable, define a default (no-argument) constructor So objects can be created via Class.newInstance(). Avoid * forms of import Be precise about what you are importing. Check that all declared imports are actually used(context and dependencies better understood). Keep scopes as small as possible so the visibility and lifetime of your objects are as small as possible. This reduces the chance of using an object in the wrong context and hiding a difficult-to-find bug. Use the containers in the standard Java library Prefer use of List, Set, and Map as returend values and not their implementation. {{{ public class ClassWithList { private LinkedList list = new LinkedList () ; public void addChild(Object o) { list.addFirst(o); } public List getAll () { return list ; } } }}} Keep things as “private as possible.” Make all non-final fields private. Once you publicize an aspect of your library (a method, a class, a field), you can never take it out. Minimize statics (except for static final constants) They make methods more context-dependent, hide possible side-effects, sometimes present synchronized access problems. and are the source of fragile, non-extensible constructions. Also, neither static variables nor methods are overridable in any useful sense in subclasses. Ensure that non-private statics have sensible values Even if no instances are ever created. (Similarly ensure that static methods can be executed sensibly.) Use static intitializers (static { ... } ) if necessary. Rationale: Better encsapsulation; less prone to subclassing snags; can be more efficient Prefere interfaces over abstract classes. If you know something is going to be a base class, your first choice should be to make it an interface, and only if you’re forced to have method definitions or member variables should you change it to an abstract class. Don't subclass concrete classes This is greatly complicated by inheriting from classes which are meant to be instantiated in their own right, where some fields, methods, and constructors are typically not relevant for subclasses,an exception to this rule, in general, for exception classes. Write methods that only do ``one thing''. In particular, separate out methods that change object state from those that just rely upon it. For a classic example in a Stack, prefer having two methods Object top() and void removeTop() versus the single method Object pop() that does both. Smaller methods are easier to understand It's probably self-evident, but several small methods, all with good names and documentation comments, are easier to understand than a single large method with the same functionality. "Method should have one exit point and at the end of the method" There could be exceptions to this rule but they should be avoided if possible. Partition methods to have short parameter lists Long parameter lists are often an indication of poor separation of concerns -- too much data is flowing between methods as separate values, rather than being encapsulated in objects or within a single method. Multithreaded Coding Conventions See Multithreaded Coding Conventions If your class requires any cleanup when the client programmer is finished with the object, place the cleanup code in a single, well-defined method, with a name dispose( ) that clearly suggests its purpose. In addition, place a boolean flag in the class to indicate whether dispose( ) has been called so that finalize( ) can check for “the termination condition”. Don't fight the language Java is a class-based, object-oriented language. That makes classes the default structuring tool, and a good Java program will take advantage of them. A design which uses lots of public fields, empty constructors, and static methods spread out over bunches of classes not related to the objects they manipulate feels wrong for Java. Conventions Home -------------------------------------------------------------------------------- CategoryConventions Hello, this ''is'' a [[test]] == New section == === Subsection === ==== Sub-subsection ==== A single newline has no effect on the layout. But an empty line starts a new paragraph. You can break lines
without starting a new paragraph. * Unordered Lists are easy to do: ** start every line with a star *** more stars means deeper levels *A newline *in a list marks the end of the list. *Of course *you can *start again. # Numbered lists are also good ## very organized ## easy to follow #A newline #in a list marks the end of the list. #New numbering starts #with 1. * You can even do mixed lists *# and nest them *#* or break lines
in lists ; word : definition of the word ; longer phrase : phrase defined : A colon indents a line or paragraph. A manual newline starts a new paragraph.
Centered text.
A horizontal dividing line: above ---- and below. Sue is reading the [[official position]] (or [[Official position]]s). *For more info see [[m:Help:Interwiki linking]]. *[[:fr:Wikipédia:Aide]]. *[[List of cities by country#Morocco]]. *[[List of cities by country#Sealand]]. *[[Help:Link|About Links]] *[[List of cities by country#Morocco|Cities in Morocco]] *In parentheses: [[kingdom (biology)|]]. *Namespace: [[Meta:Requests for adminship|]]. [[The weather in London]] is a page that doesn't exist yet. You should "sign" your comments on talk pages: : Your user name: ~~~ : Or your user name plus date/time: ~~~~ #REDIRECT [[United States]] ISBN 0123456789X RFC 123 [[media:Sg_mrob.ogg|Sound]] [[:Category:English documentation]] [[July 20]], [[1969]] , [[20 July]] [[1969]] and [[1969]]-[[07-20]] [[Special:Whatlinkshere/ Help:Editing]] and [[Special:Recentchangeslinked/ Help:Editing]] [http://www.nupedia.com Nupedia], [http://www.nupedia.com] Or just give the URL: http://www.nupedia.com. A picture: [[Image:Wiki.png]] [[Image:Wiki.png|Wikipedia - The Free Encyclopedia]] [[:Image:Wiki.png]] [[media:Wiki.png|Wikipedia]] ''Emphasize'', '''strongly''', '''''very strongly'''''. You can also write italic and bold. This is useful in mathematical formulas where you need specific font styles rather than emphasis. :F = ma You can also write in small caps. If the wiki has the templates, this can {{bsm}}be much simpler to write{{esm}}. A typewriter font, sometimes used for technical terms. You can use small text for captions. You can strike out deleted material and underline new material. Subscript: x2 Superscript: x2 or x² ε0 = 8.85 × 10−12 C² / J m. 1 [[hectare]] = [[1 E4 m²]] x2 ≥ 0 true. {||- |x2 | width=20px | || width=20px | =0 || true. |- | a || || b |} arrow → ''italics'' [[link]] arrow → ''italics'' [[link]]
arrow      →
 
''italics''
[[link]]
arrow → ''italics'' [[link]] IF a line of plain text starts with a space it will be formatted exactly as typed in a fixed-width font lines won't wrap ENDIF this is useful for: * pasting preformatted text; * algorithm descriptions; * program source code * ASCII art; * chemical structures; arrow → ''italics'' [[link]] &→ The text between '''here''' '''and here''' won't be displayed \sum_{n=0}^\infty \frac{x^n}{n!} {{Title|hovertext|This is underlined}}