Rocking On Java
Rocking On Java
Vo Minh Tam
[email protected]
Intro
Objective
Understand OOP Review all features of Java language Get you out of confusion Update latest changes in Java (since 1.5) How to make your code more beautiful
Requirement
Understand OOP Have a little knowledge with Java
pg. 2
Outline
Java Basics Java Advanced Code Convention Performance Tips Design Pattern
pg. 3
Java Basics
Outline
Java Basics
A little history Features OOP Exception Handling Collection Thread GUI & IO & Networking & Database
A little history
1991 James Gosling Oak Java Star 7: a personal hand-held remote control Includes
J2EE J2SE J2ME
pg. 6
Features
JVM
Bytecode
pg. 7
Java Basics
OOP
Class and Object Abstract class and interface Encapsulation Inheritance Polymorphism Overload
characterized by their properties and behaviors
pg. 8
Java Basics
OOP
A relationship between class/abstract class and class is a strong relationship. It is known as IS-A relationship. A relationship between class and interface is a weak relationship. It is known as Is-kind-of relationship.
pg. 9
Java Basics
OOP
Inheritance
Super and sub class Object members Constructor Calling Chain Override
instance methods static methods hiding methods
pg. 10
Java Basics
OOP
Polymorphism
association (using)
1
static
inheritance (is a)
private
Java Basics
Exception Handling
(2) Usually the result of some flaws in the user program code
pg. 13
Java Basics
Exception Handling
pg. 14
Java Basics
Exception Handling
pg. 15
Java Basics
Collection
pg. 16
Java Basics
Collection
pg. 17
Java Advanced
Outline
Java Basics Java Advanced
Scanner printf Autoboxing Enumerated Types Foreach loop Generic Types
Java 1.0
8 packages 212 classes
Java 1.1
23 packages 504 classes
Java 1.2
59 packages 1520 classes
Java 1.3
77 packages 1595 classes
Java 1.4
103 packages 2175 classes Regular Exp Logging Assertions NIO
Java 1.5
131 packages 2656 classes javax.activity, javax. management
New Events Inner class Object Serialization Jar Files International Reflection JDBC RMI
java.math, java.rmi, java.security, java.sql, java.text, java.beans java.applet, java.awt, java.io, java.lang, java.net, java.util
pg. 21
java.util.Scanner
Initialize
Scanner stdin = Scanner.create(System.in); Scanner stdin = new Scanner();
InputTest.java pg. 22
printf method
Similar to C style printf Handles
strings native types numeric types java.util.Date
OutputTest.java pg. 23
Autoboxing/Unboxing
Wrap ints into Integers Extract ints from Integers
Automatically
Notice
NullPointerException with wrapper class Inmutability
This is now legal: Integer x = 6; Integer y = 2*x + 3;
pg. 25
pg. 26
Type-safe enum
enum Day { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY } //used Day today = Day.WEDNESDAY; switch(today){ case SUNDAY: break; // }
EnumTest.java & EnumAdvanceTest.java pg. 28
Generics
ArrayList<Number> list = new ArrayList<Number>(); list.add(new Integer(5)); list.add(6); list.add(new Double(3.14159/2)); list.add(new BigInteger("123456789012301234567890") ); list.add(new Long(127L)); Number n = list.get(i);
GenericUseTest.java pg. 30
Defining Generics
public class GenericStack<T> implements Iterable<T> { private T[] data; public GenericStack() { data = (T[])new Object[MIN_SIZE]; } public T pop(){ } public void push(T item) { } public Iterator<T> iterator(){ } //since it is iterable }
pg. 31
pg. 32
pg. 34
pg. 35
Code Convention
Outline
Java Basics Java Advanced Code Convention
Class, Variable, Method Exception Handling Comment Naming
pg. 37
http://www.3cardbragrules.com/solutions/index-quality.html pg. 39
Code Convention
Class
Class Well-organized in package name MicroarrayData
layout: Layout R: double[][] G: double[][] Rb: double[][] Gb: double[][] nbrOfSlides(): int nbrOfSpots(): int swapDyes(...) append() as.data.frame(): data.frame getLayout(): Layout setLayout(layout) subtractBackground(...) normalizeWithinSlide(...) normalizeAcrossSlides(...) plot(...) plotSpatial(...) boxplot(...) hist(...) static read(...): MicroarrayData write(...)
Classes should be declared in individual files with the file name Fields matching the class name Avoid God classes -> remember Single Responsibility Principle Fields
Class (static) variables Instance variables
public class variables Methods protected package level (no access modier) private
Methods
These methods should be grouped by functionality rather than by scope or accessibility
pg. 40
Code Convention
Variable Minimize
the scope the visibility the mutability
One variable per declaration Initialize local variables where they are declared Use generics-version of a type instead of its raw type when possible
pg. 41
Code Convention
Methods
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 5 parameters -> wrap them DRY (Dont Repeat Yourself) Return empty collection instead of null
pg. 42
Code Convention
Exception Handling
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
pg. 43
Code Convention
Comments Single line comment
// TODO, // HACK
Advices
Remove unused code
http://javaworkshop.sourceforge.net/chapter4.html
pg. 44
Code Convention
Naming Naming rules:
Must consist of only letters, digits, _ and $ Cannot start with a number Cannot use Java reserved words
Naming Conventions:
Package names are all lower cases Class names are capitalized with each new word capitalized Variable names have lower case letter, new words are separated by _ or start with a capital letter (except for the first) Methods starts with verbs in camel case
E.g.: getLayout(), normalize(method, slides)
Code Convention
Naming Naming advices Names should be short but meaningful
e.g. nbrOfGrids (or ngrids) is much better than ngr
Use nouns for names of interfaces, enums, delegates, classes and variables. Not use identifiers such as String, System, out, etc are not reserved words and could be used Use as English rules Consider prefix Boolean variables and properties with can, is or has
pg. 46
Code Convention
Style good programming style means that your program is readable
pg. 47
Code Convention
Style good programming style means that your program is readable Blank lines between
Instructions Functional block
Writing multiple instructions on one line Separating an instruction onto multiple lines Adding spaces between words Declare array type Use one and only one statement per line.
pg. 48
Code Convention
Indentation
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
Line
Not excess 80 characters each line
70 characters for documentation
Wrapping Lines
Break after a comma. Break before an operator.
pg. 49
Code Convention
Declarations One declaration per line is recommended since it encourages commenting initialize local variables where theyre declared Placement
pg. 50
Code Convention
Other
String
StringBuilder > StringBuffer > String concatenation
for: Use foreach-style loop instead of for loop when possible 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
pg. 51
Performance Tips
Performance Tips
pg. 53
Performance Tips
Prefer static final Perfer static method Avoid getter and setter Use exact type when creating new object ArrayList<String> a = new ArrayList<String>() > List<String a = new ArrayList<String>() Avoid Creating Objects -> Try to reuse
Use Object Pool
pg. 54
Performance Tips
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
pg. 55
Questions?
pg. 56
References
J2SE Sang Shin course Code Convention Document from SUN Microsystems KMS Code Convention Buu Nguyen, Duy Lam http://www.jpct.net/wiki/index.php/Performance _tips_for_Android http://d.android.com/guide/practices/design/p erformance.html Calvin Austin. J2SE 1.5 in a Nutshell. http://java.sun.com/developer/technicalArticles /releases/j2se15
pg. 57