Java Conventions + Basics

Discussion in 'Programming General' started by fromdhood101, Oct 17, 2009.

Java Conventions + Basics
  1. Unread #1 - Oct 17, 2009 at 6:31 PM
  2. fromdhood101
    Joined:
    Sep 26, 2007
    Posts:
    440
    Referrals:
    0
    Sythe Gold:
    0

    fromdhood101 Forum Addict
    Banned

    Java Conventions + Basics

    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:

    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:

    Lesson 1.2: Packaging and import statements
    After the beginning comment describing your class, the packaging statement and import statements should follow.
    Example:

    Lesson 1.3: Class organization
    Your classes should be organized in the following format, from top to bottom.

    Here is an example in code form:

    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.

    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:

    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:

    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:

    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:

    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.

    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:

    4.4: Classes and Declarations
    I code differently because I originally coded C++ before going to Java, but according to Java conventions, you should:

    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:

    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:

    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):

    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):

    5.5: for Statements
    A for statement should have the following format:

    5.6: while Statements
    A while statement should have the following format:

    5.7: do-while Statements
    A do-while statement should have the following format:

    5.8: switch Statements
    A switch statement should have the following format:

    5.9: try-catch Statements

    With the finally statement added:

    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:

    One blank line should always be used in the following circumstances:

    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:

    * 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.

    * The expressions in a for statement should be separated by blank spaces

    * Casts should be followed by a blank space.

    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:

    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:

    7.3: Interfaces
    Interface names follow the same rules as class names.
    Example:

    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:

    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:

    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 ^_^
     
  3. Unread #2 - Oct 26, 2009 at 8:17 AM
  4. IBoxer
    Joined:
    Oct 11, 2009
    Posts:
    46
    Referrals:
    0
    Sythe Gold:
    0

    IBoxer Member

    Java Conventions + Basics

    nice tut. thanks.
     
  5. Unread #3 - Oct 27, 2009 at 3:39 PM
  6. super_
    Joined:
    Dec 20, 2008
    Posts:
    91
    Referrals:
    0
    Sythe Gold:
    0

    super_ Member

    Java Conventions + Basics

    why not just link to sun..
     
  7. Unread #4 - Oct 28, 2009 at 1:00 PM
  8. WCCobra
    Joined:
    Oct 7, 2009
    Posts:
    7
    Referrals:
    0
    Sythe Gold:
    0

    WCCobra Newcomer

    Java Conventions + Basics

    Great guide. Good job
     
< how make rs scripts and like that | Runescape Applet - Insecure? >

Users viewing this thread
1 guest


 
 
Adblock breaks this site