Hello.
I have been studying Java, Php and other moderate programming languages for about 2 and a half years now. It started with a science fair project that I created, but I won't get into that
Part One:
Java Conventions and why they are used:
Conventions are a sort of style of how you code Java. It helps you program and read your code more efficiently, as well as letting others read your code more efficiently. As a skilled Java developer, if you decide to release one of your sources, it needs to be easily editable by other people. Also, nothing says "noob" more than messy code.
Here are some facts of why you should follow conventions, quoted directly from Sun Microsystems, the creators of Java:
Quote:
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.
|
Lesson 1.1:
Organizing your source files
This lesson is how to organize your source files in a certain format so it is easier for others to read, interpret, and add to.
All classes should begin with a multi-line style comment, describing the class name, the version of the class, the date it was created, and the copyright notice. This example is from the Sun Microsystems website for 100% accuracy.
Example:
Quote:
/*
* Classname
*
* Version information
*
* Date
*
* Copyright notice
*/
|
Lesson 1.2:
Packaging and import statements
After the beginning comment describing your class, the packaging statement and import statements should follow.
Example:
Quote:
package mypackage.mypackageextended;
import java.io.*;
|
Lesson 1.3:
Class organization
Your classes should be organized in the following format, from top to bottom.
Quote:
1. Beginning comment
2. Packaging and import statements
3. Class or interface declaration
4. Class variables (static)
5. Instance variables: first public, then protected, then package level (no access modifier), and private.
6. Constructors
7. Methods
|
Here is an example in code form:
Quote:
/**
* Class ExampleClass for teaching Java Conventions
*
* @version 1.0
*
* Saturday, October 17, 2009
*
* There is no copyright for this class
*/
package net.codersforum.example;
import java.io.*; // Not used in this class, just for example purposes.
public class ExampleClass {
// The field of variables should come first
static int myStaticInt;
public String myPublicString;
protected boolean myProtectedBoolean;
long myPackageLevelLong;
private char myPrivateChat;
// The class constructor, used for instancing the class with parameters.
public ExampleClass(int myExampleClassInt) {
this.myStaticInt = myExampleClassInt;
}
// Methods
public static void main(String[] args) {
System.out.println("This is my ExampleClass to help you learn Java Conventions! Yay!");
}
}
|
Lesson 2:
Code indentation
This lesson will teach you how to indent your code to make it easy for others to read, this is one of the most essential part of conventions you should learn. Do not skip this lesson!
Lesson 2.1:
Line length
Your code lines should be less than 80 characters long, because they are not handled well by tools and terminals (system command windows).
Lesson 2.2:
Wrapping lines that are longer than 80 characters
If a line of your code is longer than 80 characters, it should be wrapped according to these following rules, quoted from the Sun Microsystems site.
Quote:
* 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.
|
The following is a direct quote on how to indent from the Java Conventions Guide:
Code:
Here are some examples of breaking method calls:
someMethod(longExpression1, longExpression2, longExpression3,
longExpression4, longExpression5);
var = someMethod1(longExpression1,
someMethod2(longExpression2,
longExpression3));
Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.
longName1 = longName2 * (longName3 + longName4 - longName5)
+ 4 * longname6; // PREFER
longName1 = longName2 * (longName3 + longName4
- longName5) + 4 * longname6; // AVOID
Following are two examples of indenting method declarations. The first 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.
//CONVENTIONAL INDENTATION
someMethod(int anArg, Object anotherArg, String yetAnotherArg,
Object andStillAnother) {
...
}
//INDENT 8 SPACES TO AVOID VERY DEEP INDENTS
private static synchronized horkingLongMethodName(int anArg,
Object anotherArg, String yetAnotherArg,
Object andStillAnother) {
...
}
Line wrapping for if statements should generally use the 8-space rule, since conventional (4 space) indentation makes seeing the body difficult. For example:
//DON'T USE THIS INDENTATION
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) { //BAD WRAPS
doSomethingAboutIt(); //MAKE THIS LINE EASY TO MISS
}
//USE THIS INDENTATION INSTEAD
if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) {
doSomethingAboutIt();
}
//OR USE THIS
if ((condition1 && condition2) || (condition3 && condition4)
||!(condition5 && condition6)) {
doSomethingAboutIt();
}
Here are three acceptable ways to format ternary expressions:
alpha = (aLongBooleanExpression) ? beta : gamma;
alpha = (aLongBooleanExpression) ? beta
: gamma;
alpha = (aLongBooleanExpression)
? beta
: gamma;
Here is my take on indenting code:
Anything inside a code block should be tabbed (indented) once more than the code blocks indentation. Here is an example:
Quote:
boolean indent = true;
int indentMore = 1;
if (indent) {
// Indented line (4 spaces or one tab)
System.out.println("My code is indented! Yay!");
if (indentMore == 1) {
// Indented 4 spaces more than the opening brace, or 1 tab)
System.out.println("My code is indented more!");
}
}
|
Lesson 3:
Comments
A comment is something that will allow you to write in English (or any other language) to explain how your code works.
Your code should be commented so others can understand it in English, without having to follow your code around and figure out what it does.
Java has 3 types of comments, block comments, end-of-line comments, and doc comments.
3.1:
Block comments
A block comment is a comment that can be extended for several lines. You write block comments the same way that you write comments in C.
To open a block comment, use this:
To close a block comment, use this:
Here is an example of a block comment:
Quote:
/*
A block comment!
Yay!
*/
|
Everything inside a block comment block is completely ignored by the Java Compiler.
3.2:
End-of-line comments
Another type of comment is the end-of-line comment, for which everything on the line after the end-of-line comment is initiated will be ignored.
To start an end-of-line comment, use this:
There is no closing to an end-of-line comment. It ends at the end of a line.
Here is an example of an end-of-line comment:
Quote:
// Yay I'm an end-of-line comment!
|
3.3:
JavaDoc is a very powerful tool that allows you to document large projects for later use. I will not go in-depth on how JavaDoc works, but for a JavaDoc guide, you can go here:
http://java.sun.com/javadoc/writingdoccomments (This is a guide, I'm not advertising)
Lesson 4:
Declarations
This is a guide on how to use conventions to style your declarations properly.
4.1:
Per-Line declarations
According to Java Conventions, you should make only one statement per-line, because it encourages commenting. Here is an example:
Quote:
int myInt; // My Integer
boolean myboolean; // My Boolean
|
4.2:
Initializing Variables
You should initialize, or assign a value to your variables upon declaration, unless a calculation is performed first setting the value of the variable. Here is how you properly declare and initialize a variable.
Quote:
|
int myInitializedInt = 1; // Initialized by giving it a value
|
4.3:
Declaration Placement
Try to declare your variables first inside each code block, as to not confuse any programmer who doesn't know what the variables are, or the scope in which they are placed (scope is a slightly advanced concept, ignore the previous statement unless you know what it is).
Here is an example:
Quote:
void myMethod() {
int myInteger = 2; // Placed at the beginning of the method block
if (myInteger == 2) {
int myInteger2 = 0; // Beginning of "if" block
// Code using myInteger2 here
}
}
|
4.4:
Classes and Declarations
I code differently because I originally coded C++ before going to Java, but according to Java conventions, you should:
Quote:
* 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 "{"
Here is an example of the above rules, taken from the Java Conventions official tutorial:
|
Quote:
class Sample {
int ivar1;
int ivar2;
Sample(int i, int j) {
ivar1 = i;
ivar2 = j;
}
int emptyMethod() {}
...
}
|
Lesson 5:
Statements
A statement in Java is basically a piece of code that does something. Pretty blunt, but thats pretty much it. There are ways statements should be made.
5.1:
Simple Statements
Each line should contain just one statement. For example:
Quote:
intOne++; // Correct
intTwo--; // Correct
intOne++; intTwo--; // Wrong
|
5.2:
Compound Statements
Compound statements are a number of statements that are contained in a code block ({ and }). Here are the rules for compound statements, quoted from the Java Conventions tutorial:
Quote:
# 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.
|
5.3:
return statements
A return statement is a statement that belongs in a method that ends a method and returns a value (in this case, null if the method is declared as void). A return statement with a value should not use parentheses unless they make the return value more obvious in some way.
For example (taken from Conventions official tutorial):
Quote:
return;
return myDisk.size();
return (size ? size : defaultSize);
|
5.4:
if, if-else, if else-if else Statements
The if-else class of statements should be formatted as so (taken from Conventions tutorial):
Quote:
if (condition) {
statements;
}
if (condition) {
statements;
} else {
statements;
}
if (condition) {
statements;
} else if (condition) {
statements;
} else {
statements;
}
|
5.5:
for Statements
A for statement should have the following format:
Quote:
for (initialization; condition; update) {
statements;
}
|
5.6:
while Statements
A while statement should have the following format:
Quote:
while (condition) {
statements;
}
|
5.7:
do-while Statements
A do-while statement should have the following format:
Quote:
do {
statements;
} while (condition);
|
5.8:
switch Statements
A switch statement should have the following format:
Quote:
switch (condition) {
case ABC:
statements;
/* falls through */
case DEF:
statements;
break;
case XYZ:
statements;
break;
default:
statements;
break;
}
|
5.9:
try-catch Statements
Quote:
try {
statements;
} catch (ExceptionClass e) {
statements;
}
|
With the finally statement added:
Quote:
try {
statements;
} catch (ExceptionClass e) {
statements;
} finally {
statements;
}
|
Lesson 6:
White Space
White Space in Java is completely ignored by the Java Compiler. Your Java code will work nomatter what amount of white space there is. White space is a term for the use of blank lines, blank tabs, and blank spaces to properly format your Java code.
6.1:
Blank Lines
Blank lines are created by pressing the enter key (no, really?). They are used to help organize and space out your code to maximize readability.
Two blank lines should always be used in the following circumstances:
Quote:
* Between sections of a source file
* Between class and interface definitions
|
One blank line should always be used in the following circumstances:
Quote:
* Between methods
* Between the local variables in a method and its first statement
* Before a block or single-line comment
* Between logical sections inside a method to improve readability
|
Lesson 6.2:
Blank Spaces
Blank spaces are characters that are entered in by pressing the space bar (duh?). They are used in Java to help people understand your code better. A majority of this is taken directly from the Java Conventions guide, as it is pretty simple in itself. A few code examples have been added.
* A keyword followed by a parenthesis should be separated by a space.
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 occur after commas in a list of arguments, for example:
Quote:
|
myMethod(param1, param2, param3);
|
* 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.
Quote:
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
Quote:
|
for (expr1; expr2; expr3)
|
* Casts should be followed by a blank space.
Quote:
myMethod((byte) aNum, (Object) x);
myMethod((int) (cp + 5), ((int) (i + 3))
+ 1);
|
Lesson 7:
Naming Conventions
According to conventions, you should name your variables, classes, methods, and packages a certain way. This is how you do it.
7.1:
Packages
The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, currently com, edu, gov, mil, net, org, or one of the English two-letter codes identifying countries as specified in ISO Standard 3166, 1981.
Subsequent components of the package name vary according to an organization's own internal naming conventions. Such conventions might specify that certain directory name components be division, department, project, machine, or login names.
Example:
Quote:
|
package net.codersforum.core;
|
7.2:
Classes
Class names should be nouns, in mixed case with the first letter of each internal word capitalized. Try to keep your class names simple and descriptive. Use whole words-avoid acronyms and abbreviations (unless the abbreviation is much more widely used than the long form, such as URL or HTML).
Example:
Quote:
class ReadWrite;
class WriteDataToClient;
|
7.3:
Interfaces
Interface names follow the same rules as class names.
Example:
Quote:
interface Storage;
interface Stream;
|
7.4:
Methods
Methods should be verbs, in mixed case with the first letter lowercase, with the first letter of each internal word capitalized.
Example:
7.5:
Variables
Except for variables, all instance, class, and class constants are in mixed case with a lowercase first letter. Internal words start with capital letters. Variable names should not start with underscore _ or dollar sign $ characters, even though both are allowed.
Variable names should be short yet meaningful. The choice of a variable name should be mnemonic- that is, designed to indicate to the casual observer the intent of its use. One-character variable names should be avoided except for temporary "throwaway" variables. Common names for temporary variables are i, j, k, m, and n for integers; c, d, and e for characters.
Example:
Quote:
int i;
int myInteger;
char c;
|
7.6:
Constants
The names of variables declared class constants and of ANSI constants should be all uppercase with words separated by underscores ("_"). (ANSI constants should be avoided, for ease of debugging.)
Example:
Quote:
|
static final int MY_FINAL_INTEGER = 100;
|
And there you go, there are the basic Java Conventions. If you want to learn 100% Java Conventions, feel free to visit their official tutorial, which is what this tutorial is based off, here:
http://java.sun.com/docs/codeconv/ht...nvTOC.doc.html
I really thank you for taking the time to learn the Java Conventions.
- Hood
