rocking on java

Upload: an-nguyen-van

Post on 06-Apr-2018

246 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/3/2019 Rocking on Java

    1/57

    Rocking on JavaVo Minh Tam

    [email protected]

  • 8/3/2019 Rocking on Java

    2/57

    Intro

    Objective Understand OOP

    Review all features of Java language Get you out of confusion

    U date latest chan es in Java since 1.5

    pg. 2

    How to make your code more beautiful

    Requirement

    Understand OOP Have a little knowledge with Java

  • 8/3/2019 Rocking on Java

    3/57

    Outline

    Java Basics

    Java Advanced

    Code Convention

    Performance Tips

    pg. 3

    es gn a ern

  • 8/3/2019 Rocking on Java

    4/57

    Java Basics

  • 8/3/2019 Rocking on Java

    5/57

    Outline

    Java Basics A little history

    Features OOP

    Exception Handling

    pg. 5

    Thread

    GUI & IO & Networking & Database

    Java Advanced

    Code Convention

    Performance Tips

    Design Pattern

  • 8/3/2019 Rocking on Java

    6/57

    A little history

    1991

    James Gosling

    Oak Java

    Star 7: a personal hand-held remote

    pg. 6

    con ro Includes

    J2EE

    J2SE

    J2ME

  • 8/3/2019 Rocking on Java

    7/57

    Features

    JVM Bytecode

    Garbage Collection

    Code Security

    pg. 7

    ass oa er Bytecode verifier

  • 8/3/2019 Rocking on Java

    8/57

    Java Basics

    Class and Object

    Abstract class and interface

    Encapsulation

    Inheritance

    OOP

    pg. 8

    Polymorphism Overload

    characterized by their properties and behaviors

  • 8/3/2019 Rocking on Java

    9/57

    Java Basics

    Abstract class and interface Same

    Derived class must implement all abstract methods

    Cannot create instances by using new operators

    The purpose in POLYMORPHISM

    Difference from abstract class

    OOP

    pg. 9

    [I] Have multiple interface in one class [I] CANNOT include nonabstract method

    [I] Interface is NOT designed to be superclass. Interface isdesigned to add some behaviors to a class.

    A relationship between class/abstract class and class is astrong relationship. It is known as IS-A relationship.

    A relationship between class and interface is a weakrelationship. It is known as Is-kind-of relationship.

  • 8/3/2019 Rocking on Java

    10/57

    Java Basics

    Inheritance Super and sub class

    Object members Constructor Calling Chain

    Override

    OOP

    pg. 10

    instance methods

    static methods hiding methods

    Casting

    Final class and method

  • 8/3/2019 Rocking on Java

    11/57

    Java Basics

    PolymorphismOOP

    pg. 11

    Ph.D Nguyen Hua Phung, Dept of CSE

  • 8/3/2019 Rocking on Java

    12/57

    Unified Modeling Language (UML) class diagram

    10..*

    abstractstatic

    association

    (using)

    privateinheritance

    (is a)

  • 8/3/2019 Rocking on Java

    13/57

    Java Basics

    Error vs. Exception Immediate subclasses of Throwable

    Error

    Exception

    (1) Generally beyond the control of user programs Out of memory errors

    Exception Handling

    pg. 13

    ar s cras

    (2) Usually the result of some flaws in the user programcode

    Checked Exception vs. Unchecked

    Exception

  • 8/3/2019 Rocking on Java

    14/57

    Java Basics

    Error vs. Exception

    Checked Exception vs. Unchecked

    Exception Common unchecked exception

    NullPointerException

    Exception Handling

    pg. 14

    ArithmetrictException IllegalArgumentException

    IllegalStateException

    UnsupportedOperationException

    AssertionError

  • 8/3/2019 Rocking on Java

    15/57

    Java Basics

    Exception Handling

    pg. 15

  • 8/3/2019 Rocking on Java

    16/57

    Java Basics

    Collection

    pg. 16

  • 8/3/2019 Rocking on Java

    17/57

    Java Basics

    Normal Array vs. List

    Vector vs. ArrayList

    Traversing

    Collection

    pg. 17

  • 8/3/2019 Rocking on Java

    18/57

    Java Advanced

  • 8/3/2019 Rocking on Java

    19/57

    Outline

    Java Basics

    Java Advanced

    Scanner printf

    pg. 19

    Enumerated Types

    Foreach loop

    Generic Types

    Code Convention

    Performance Tips

    Design Pattern

    Java 1 0 Java 1 1 Java 1 2 Java 1 3 Java 1 4 Java 1 5

  • 8/3/2019 Rocking on Java

    20/57

    java.nio, javax.imageio,javax.net, javax.print,

    javax.security, org.w3c

    javax.activity,javax.

    management

    Java 1.08 packages

    212 classes

    Java 1.123 packages

    504 classes

    Java 1.259 packages

    1520 classes

    Java 1.377 packages

    1595 classes

    Java 1.4103 packages

    2175 classes

    Java 1.5131 packages

    2656 classes

    New Events

    Inner class

    Object

    SerializationJar Files

    International

    JFC/Swing

    Drag and

    Drop

    Java2DCORBA

    JNDI

    Java Sound

    Timer

    Regular ExpLogging

    Assertions

    NIO

    java.applet, java.awt, java.io, java.lang, java.net, java.util

    java.math, java.rmi, java.security, java.sql, java.text, java.beans

    javax.accessibility, javax.swing, org.omg

    avax.naming, javax.sound,javax.transactionReflectionJDBC

    RMI

  • 8/3/2019 Rocking on Java

    21/57

    Other New Features

    Static import: import static java.Math.*;

    Variable length argument lists.

    pg. 21

    Semaphores

    Metadata

  • 8/3/2019 Rocking on Java

    22/57

    java.util.Scanner

    Initialize Scanner stdin = Scanner.create(System.in);

    Scanner stdin = new Scanner();

    Read from keyboard

    pg. 22

    hasNextXXX()

    InputTest.java

  • 8/3/2019 Rocking on Java

    23/57

    printf method

    Similar to C style printf

    Handles

    strings

    native types

    pg. 23

    java.util.Date

    See java.util.Formatter for details

    OutputTest.java

  • 8/3/2019 Rocking on Java

    24/57

    Autoboxing/Unboxing

    Wrap ints into Integers

    Extract ints from Integers Automatically

    Notice

    pg. 24

    NullPointerException with wrapper class Inmutability

    This is now legal:Integer x = 6; //6 is boxed

    Integer y = 2*x + 3; //x is unboxed, 15 is boxed

    AutoBoxTest.java

  • 8/3/2019 Rocking on Java

    25/57

    Object Only Performance

    int x = 6;

    int y = 2*x;

    Code:

    0: bipush 6

    pg. 25

    : s ore_

    3: iconst_2

    4: iload_1

    5: imul

    6: istore_2

  • 8/3/2019 Rocking on Java

    26/57

    Object Only Performance

    Integer x = 6;Integer y = 2*x;

    Code:

    0: bipush 6

    2: invokestatic #2;

    //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;

    pg. 26

    5: astore_1

    6: iconst_2

    7: aload_1

    8: invokevirtual #3;

    //Method java/lang/Integer.intValue:()I

    11: imul

    12: invokestatic #2;

    //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer;

    15: astore_2

  • 8/3/2019 Rocking on Java

    27/57

    Object Only Performance

    Integer x = Integer.valueOf(6);

    Integer y = Integer.valueOf(2 * x.IntValue);

    pg. 27

    Generates the same byte code.

    EnumTest.java & EnumAdvanceTest.java

  • 8/3/2019 Rocking on Java

    28/57

    Type-safe enum

    enum Day { SUNDAY, MONDAY, TUESDAY,WEDNESDAY, THURSDAY,FRIDAY, SATURDAY }

    //usedDay today = Day.WEDNESDAY;

    pg. 28

    switch(today){case SUNDAY:

    break;

    //}

    EnumTest.java & EnumAdvanceTest.java

  • 8/3/2019 Rocking on Java

    29/57

    More Complex Enum

    enum Suit {CLUBS(Color.BLACK),DIAMONDS(Color.RED),

    HEARTS(Color.RED),SPADES(Color.BLACK);

    pg. 29

    private Color color;

    Suit(Color color) { this.color = color; }

    public Color getColor() { return color; }}

    EnumTest.java & EnumAdvanceTest.java

  • 8/3/2019 Rocking on Java

    30/57

    Generics

    ArrayList list = newArrayList();

    list.add(new Integer(5));list.add(6);

    pg. 30

    s .a new ou e . ;list.add(new

    BigInteger("123456789012301234567890"));

    list.add(new Long(127L));

    Number n = list.get(i);GenericUseTest.java

  • 8/3/2019 Rocking on Java

    31/57

    Defining Generics

    public class GenericStack implements Iterable{

    private T[] data;

    public GenericStack() {

    data = (T[])new Object[MIN_SIZE];

    pg. 31

    public T pop(){ }

    public void push(T item) { }

    public Iterator iterator(){ } //since it is iterable

    }

  • 8/3/2019 Rocking on Java

    32/57

    Defining Generic Iterator

    //inner class of GenericStack

    private class GenericStackIterator implements Iterator {

    int index;

    GenericStackTestIterator() {

    index = top;}

    public boolean hasNext() { return index >= 0; }

    pg. 32

    public T next() {

    if(index < 0) {

    throw new java.util.NoSuchElementException();

    }

    T item = data[index];

    index--;return item;

    }

    public void remove() {

    throw new UnsupportedOperationException( )

    }

    ( )

  • 8/3/2019 Rocking on Java

    33/57

    For each loop (arrays)

    double[] array = {2.5, 5.2, 7.9, 4.3, 2.0};

    for(double d: array){

    S stem.out. rintln d

    pg. 33

    }

    Iterate (forward) through the array withoutpaying attention to indices.

    ForLoopTest.java

    F h l (C ll ti )

  • 8/3/2019 Rocking on Java

    34/57

    For each loop (Collections)

    ArrayList list = newArrayList();

    list.add(7);list.add(15);

    pg. 34

    s .a - 7 ;for(Integer number: list){

    System.out.println(number);

    }

    F h l

  • 8/3/2019 Rocking on Java

    35/57

    For each loop enums

    for( Suit s: Suit.values()){

    System.out.println(s.getColor());

    }

    pg. 35

    values() returns an Iterator for enum types

  • 8/3/2019 Rocking on Java

    36/57

    Code Convention

    O tli

  • 8/3/2019 Rocking on Java

    37/57

    Outline

    Java Basics

    Java Advanced

    Code Convention Class, Variable, Method

    pg. 37

    Comment Naming

    Performance Tips

    Design Pattern

    P i St l G id li

  • 8/3/2019 Rocking on Java

    38/57

    Programming Style Guidelines

    80% of the lifetime cost of a piece ofsoftware goes to maintenance.

    Hardly any software is maintained for itswhole life by the original author.

    pg. 38

    readability of the software, allowingprogrammers to understand new codemore quickly and thoroughly.

    If you ship your source code as aproduct, you need to make sure it is aswell packaged and clean as any other

    product you create.

    Programming Style Guidelines

  • 8/3/2019 Rocking on Java

    39/57

    Programming Style Guidelines

    pg. 39

    http://www.3cardbragrules.com/solutions/index-quality.html

    Code Convention

  • 8/3/2019 Rocking on Java

    40/57

    Code Convention

    Well-organized in package

    Classes should be declared inindividual files with the file name

    matching the class name Avoid God classes -> remember

    Single Responsibility Principle

    ClassMicroarrayData

    layout: Layout

    R: double[][]

    G: double[][]

    Rb: double[][]Gb: double[][]

    nbrOfSlides(): int

    nbrOfSpots(): int

    swa D es ...

    Class name

    Fields

    pg. 40

    e s Class (static) variables

    Instance variables public class variables

    protected

    package level (no access modifier)

    private

    Methods These methods should be grouped by

    functionality rather than by scope or

    accessibility

    append()

    as.data.frame(): data.framegetLayout(): Layout

    setLayout(layout)

    subtractBackground(...)

    normalizeWithinSlide(...)

    normalizeAcrossSlides(...)plot(...)

    plotSpatial(...)

    boxplot(...)

    hist(...)

    static read(...): MicroarrayData

    write(...)

    Methods

    Code Convention

  • 8/3/2019 Rocking on Java

    41/57

    Code Convention

    Minimize the scope

    the visibility

    the mutability

    One variable per declaration

    Variable

    pg. 41

    Use generics-version of a type instead of its rawtype when possible

    Code Convention

  • 8/3/2019 Rocking on Java

    42/57

    Code Convention

    only one job

    Avoid methods which have more than 30 lines of code

    Public methods must validate their input arguments

    Avoid writing methods accepting any more than 5parameters -> wrap them

    DRY (Dont Repeat Yourself)

    Methods

    pg. 42

    Return empty collection instead of null

    Code Convention

  • 8/3/2019 Rocking on Java

    43/57

    Code Convention

    Do not use status code to communicate error conditions

    Never declare an empty catch block

    Only use the finally block to release resources from a try

    statement Catch with specific exception first

    Catch as lately as possible

    Exception Handling

    pg. 43

    Code Convention

  • 8/3/2019 Rocking on Java

    44/57

    Code Convention

    Single line comment

    // TODO, // HACK

    Block comment

    Special Javadoc comment

    /***/

    Comments

    pg. 44

    Popular tags @author

    @version

    @param

    @return

    @throws @see

    @since

    @deprecated

    Advices

    Remove unused code

    http://javaworkshop.sourceforge.net/chapter4.html

    Code Convention

  • 8/3/2019 Rocking on Java

    45/57

    Code Convention

    Naming rules:

    Must consist of only letters, digits, _ and $

    Cannot start with a number

    Cannot use Java reserved words

    Naming Conventions:

    Naming

    pg. 45

    Class names are capitalized with each new wordcapitalized

    Variable names have lower case letter, new words areseparated by _ or start with a capital letter (except for the

    first) Methods starts with verbs in camel case

    E.g.: getLayout(), normalize(method, slides)

    Constants are all in upper case

    Code Convention

  • 8/3/2019 Rocking on Java

    46/57

    Code Convention

    Naming advices

    Names should be short but meaningful e.g. nbrOfGrids (orngrids) is much better than ngr

    Use nouns for names of interfaces, enums,delegates, classes and variables.

    Naming

    pg. 46

    o use en ers suc as r ng, ys em, ou , e care not reserved words and could be used

    Use as English rules

    Consider prefix Boolean variables and propertieswith can, is or has

    Code Convention

  • 8/3/2019 Rocking on Java

    47/57

    Code Convention

    good programming style means that your programis readable

    Style

    pg. 47

    Code Convention

  • 8/3/2019 Rocking on Java

    48/57

    Code Convention

    good programming style means that your programis readable

    Blank lines between Instructions Functional block

    Writin multi le instructions on one line

    Style

    pg. 48

    Separating an instruction onto multiple lines Adding spaces between words

    Declare array type

    Use one and only one statement per line.

    Code Convention

  • 8/3/2019 Rocking on Java

    49/57

    Code Convention

    Block section Indent with tab character (4 characters)

    if else, while, do, try catch Do not nest code any more than 3 levels of

    depth

    Indentation

    pg. 49

    Line Not excess 80 characters each line

    70 characters for documentation

    Wrapping Lines Break after a comma.

    Break before an operator.

    Code Convention

  • 8/3/2019 Rocking on Java

    50/57

    Code Convention

    One declaration per line is recommended sinceit encourages commenting

    initialize local variables where theyre declared

    Placement

    Declarations

    pg. 50

    Code Convention

  • 8/3/2019 Rocking on Java

    51/57

    Code Convention

    String StringBuilder > StringBuffer > String concatenation

    enum

    Use enum types instead of constants when possible for: Use foreach-style loop instead of for

    Other

    pg. 51

    switch: include default case

    Do not use magic number

    Do not miss access modifier Avoid boxing and unboxing value types

    Use prefix in UI components

  • 8/3/2019 Rocking on Java

    52/57

    Performance Ti s

    Performance Tips

  • 8/3/2019 Rocking on Java

    53/57

    p

    pg. 53

    Performance Tips

  • 8/3/2019 Rocking on Java

    54/57

    p

    Prefer static final

    Perfer static method

    Avoid getter and setter

    Use exact type when creating new object ArrayList a = new ArrayList() > List

  • 8/3/2019 Rocking on Java

    55/57

    p

    Avoid use Collection, use native array

    Avoid Enums Where You Only Need Ints public enum Shrubbery { GROUND, CRAWLING, HANGING }

    Use public static final int instead

    Use Floating-Point Carefully Use double instead of float

    pg. 55

    Know And Use The Libraries Use System.arraycopy, String.indexOf

    Questions?

  • 8/3/2019 Rocking on Java

    56/57

    pg. 56

    References

  • 8/3/2019 Rocking on Java

    57/57

    J2SE Sang Shin course

    Code Convention Document from SUNMicrosystems

    KMS Code Convention Buu Nguyen, Duy Lam

    http://www.jpct.net/wiki/index.php/Performance

    pg. 57

    _ ps_ or_ n ro

    http://d.android.com/guide/practices/design/performance.html

    Calvin Austin. J2SE 1.5 in a Nutshell.

    http://java.sun.com/developer/technicalArticles/releases/j2se15