Effective Java – General Programming Global Server Dept. Hu Qiongkai

Slides:



Advertisements
Similar presentations
CMSC 132: Object-Oriented Programming II Nelson Padua-Perez William Pugh Department of Computer Science University of Maryland, College Park.
Advertisements

New features in JDK 1.5 Can these new and complex features simplify Java development?
Classes and Objects. What is Design? The parts of the software including – what information each part holds – what things each part can do – how the various.
Java Review Interface, Casting, Generics, Iterator.
Written by: Dr. JJ Shepherd
CERTIFICATION OBJECTIVES Use Class Members Develop Wrapper Code & Autoboxing Code Determine the Effects of Passing Variables into Methods Recognize when.
Introduction to Programming Lesson 1. Objectives Skills/ConceptsMTA Exam Objectives Understanding Computer Programming Understand computer storage and.
Generic programming in Java
Big Java by Cay Horstmann Copyright © 2009 by John Wiley & Sons. All rights reserved. Chapter 17 – Generic Programming.
Effective Java Gruppe Gul Items vi vil uddybe: # 15Minimize Mutability # 23 Don’t use raw types in new code # 47Know and use Libraries # 63Include failure-capture.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
11-Jun-15 Generics. A generic is a method that is recompiled with different types as the need arises The bad news: Instead of saying: List words = new.
CS 206 Introduction to Computer Science II 01 / 21 / 2009 Instructor: Michael Eckmann.
1 Chapter 4 Language Fundamentals. 2 Identifiers Program parts such as packages, classes, and class members have names, which are formally known as identifiers.
Using ArrayList. Lecture Objectives To understand the foundations behind the ArrayList class Explore some of the methods of the ArrayList class.
Java 1.5 & Effective Java Fawzi Emad Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
1 Generics and Using a Collection Generics / Parameterized Classes Using a Collection Customizing a Collection using Inheritance Inner Classes Use of Exceptions.
Chapter 14 Generics and the ArrayList Class Copyright © 2010 Pearson Addison-Wesley. All rights reserved.
Java Review Nelson Padua-Perez Chau-Wen Tseng Department of Computer Science University of Maryland, College Park.
CS 206 Introduction to Computer Science II 01 / 23 / 2009 Instructor: Michael Eckmann.
Java Data Types  Everything is an Object  Except Primitive Data Types  For efficiency  Platform independent  Portable  “slow”  Objects are often.
15-Jul-15 Generics. ArrayList s and arrays A ArrayList is like an array of Object s, but... Arrays use [ ] syntax; ArrayList s use object syntax An ArrayList.
© Amir Kirsh Object Oriented Programming with Java Written by Amir Kirsh.
Classes, Objects, Arrays, Collections and Autoboxing Dr. Andrew Wallace PhD BEng(hons) EurIng
Java Generics.
By Nicholas Policelli An Introduction to Java. Basic Program Structure public class ClassName { public static void main(String[] args) { program statements.
Chapter 21 Generics 1. Generics - Overview Generic Methods specify a set of related methods Generic classes specify a set of related types Software reuse.
07 Coding Conventions. 2 Demonstrate Developing Local Variables Describe Separating Public and Private Members during Declaration Explore Using System.exit.
Chapter 1: Introducing JAVA. 2 Introduction Why JAVA Applets and Server Side Programming Very rich GUI libraries Portability (machine independence) A.
GENERIC COLLECTIONS. Type-Wrapper Classes  Each primitive type has a corresponding type- wrapper class (in package java.lang).  These classes are called.
Effective Java: Creating and Destroying Objects Last Updated: Fall 2012.
Java Quiz Bowl A fun review of the Java you should know from CMPT 201 If you don’t know the answers - this week is for you to study up!
ArrayList, Multidimensional Arrays
Chris Kiekintveld CS 2401 (Fall 2010) Elementary Data Structures and Algorithms Vectors, Strings, and Enumeration Data Types.
1 Object Oriented Programming Lecture IX Some notes on Java Performance with aspects on execution time and memory consumption.
© 2007 Lawrenceville Press Slide 1 Chapter 10 Arrays  Can store many of the same kind of data together  Allows a collection of related values to be stored.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Chapter 7 Arrays. A 12-element array Declaring and Creating Arrays Arrays are objects that occupy memory Created dynamically with keyword new int c[]
Java SE 8 for Programmers, Third Edition
Java™ How to Program, 9/e © Copyright by Pearson Education, Inc. All Rights Reserved.
CS 206 Introduction to Computer Science II 09 / 10 / 2009 Instructor: Michael Eckmann.
Modern Software Development Using C#.NET Chapter 5: More Advanced Class Construction.
E FFECTIVE C# 50 Specific Ways to Improve Your C# Second Edition Bill Wagner محمد حسین سلطانی.
Best Practices. Contents Bad Practices Good Practices.
Chapter 14 Generics and the ArrayList Class Slides prepared by Rose Williams, Binghamton University Copyright © 2008 Pearson Addison-Wesley. All rights.
Java 5 Part 1 CSE301 University of Sunderland Harry Erwin, PhD.
1 Generics Chapter 21 Liang, Introduction to Java Programming.
Aug 9, CMSC 202 ArrayList. Aug 9, What’s an Array List ArrayList is  a class in the standard Java libraries that can hold any type of object.
AP Computer Science edition Review 1 ArrayListsWhile loopsString MethodsMethodsErrors
SPL/2010 Synchronization 1. SPL/2010 Overview ● synchronization mechanisms in modern RTEs ● concurrency issues ● places where synchronization is needed.
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
CMSC 132: Object-Oriented Programming II Java Constructs Department of Computer Science University of Maryland, College Park.
This recitation 1 An interesting point about A3: Using previous methods to avoid work in programming and debugging. How much time did you spend writing.
SOEN 343 Software Design Section H Fall 2006 Dr Greg Butler
Java Generics. It is nice if we could write a single sort method that could sort array of any type of elements: – Integer array, – String array, Solution:
Effective Java: General Programming Last Updated: Fall 2008.
More Java: Static and Final, Abstract Class and Interface, Exceptions, Collections Framework 1 CS300.
1 CSC 2053 New from AutoBoxing 3 Before J2SE 5.0, working with primitive types required the repetitive work of converting between the primitive.
CSE 1201 Object Oriented Programming ArrayList 1.
CS 61B Data Structures and Programming Methodology July 8, 2008 David Sun.
Written by: Dr. JJ Shepherd
Bart van Kuik Application Developer Oracle Corporation.
Data Types and Control Structures CS3250. Java Data Types Everything is an Object Except Primitive Data Types –For efficiency –Platform independent Portable.
C# Fundamentals An Introduction. Before we begin How to get started writing C# – Quick tour of the dev. Environment – The current C# version is 5.0 –
JAVA MULTIPLE CHOICE QUESTION.
Can store many of the same kind of data together
© A+ Computer Science - Arrays and Lists © A+ Computer Science -
Object Oriented Programming in java
Can store many of the same kind of data together
Presentation transcript:

Effective Java – General Programming Global Server Dept. Hu Qiongkai

Content  Minimize the scope of local variables  Beware performance of string concatenation  Prefer for-each loops to traditional for loops  Refer to objects by their interfaces  Avoid float/double if exact answers required  Prefer interfaces to reflection  Prefer primitive types to boxed primitives  Avoid strings where other types are more appropriate  Other practical principals

Minimize the scope of local variables  Before use a variable  declare variable  variable initialization  Variable scope  Inside a block try { String s = “”; } catch (Exception e){}  in for statement // Preferred idiom for iterating over a collection since JDK1.5 for (Element e : c) { doSomething(e); } // No for-each loop or generics before release 1.5 for (Iterator i = c.iterator(); i.hasNext(); ) { doSomething((Element) i.next()); }  outside a block String s = null; try { s = “”; } catch (Exception e){}

Minimize the scope of local variables(2)  cut-and-paste error Iterator i = c.iterator(); while (i.hasNext()) { doSomething(i.next()); }... Iterator i2 = c2.iterator(); while (i.hasNext()) { // runtime BUG! doSomethingElse(i2.next()); }  Better practice  Time to declare variable: at where it is first used  Initialization tip: in a try/catch block, if variable needs be used outside block, should initilize it outside try/catch  prefer ‘for’ loops to ‘while’ loops  keep methods small and focused for (Iterator i = c.iterator(); i.hasNext(); ) { doSomething(i.next()); }... // Compile-time error - cannot find symbol i for (Iterator i2 = c2.iterator(); i.hasNext(); ) { doSomething(i2.next()); }

Beware performance of string concatenation  Simple concatenation with ‘+’ public String concat4(String s1, String s2, String s3, String s4) { return s1 + s2 + s3 + s4; } # Before JDK5  Using ‘+’ repeatedly to concatenate n strings requires time quadratic in n(n 2 ).  String is immutable, for concatenation with ‘+’, needs characters copied and a new result String object created. # Since JDK5  auto optimized by compiled into using StringBuilder.append().  compiled sample: String ss = (new StringBuilder("ok")).append(s).append("xyz").append(5).toString();

Beware performance of string concatenation(2)  Complex concatenation with ‘+’  what if concatenation in a ‘for’ statement? Random rand = new Random(); for (int i = 0; i < 10; i++) { s = s + rand.nextInt(1000) + " "; } # compiled sample: StringBuilder result = new StringBuilder(); for(int i = 0; i < 10; i++) { s = (new StringBuilder(String.valueOf(s))).append(rand.nextInt(1000)).append(" ").toString(); } # Tip  new a StringBuilder Object for each item in ‘for’ statement

Beware performance of string concatenation(3)  Better performance: use StringBuilder/StringBuffer instead  java.lang.StringBuilder mutable sequence of characters no guarantee for thread safe  java.lang.StringBuffer thread-safe, mutable sequence of characters Class Hierarchy

Prefer for-each loops to traditional for loops  traditional for loops // No longer the preferred idiom to iterate over a collection! for (Iterator i = c.iterator(); i.hasNext(); ) { doSomething((Element) i.next()); // (No generics before 1.5) } // No longer the preferred idiom to iterate over an array! for (int i = 0; i < a.length; i++) { doSomething(a[i]); }  for-each loops // The preferred idiom for iterating over collections and arrays for (Element e : elements) { doSomething(e); }  advantages by using for-each  code clarity  no performance penalty, even slight better during loop an array, only computes index once  bug prevention?

Prefer for-each loops to traditional for loops(2)  Can you spot the bug? enum Suit { CLUB, DIAMOND, HEART, SPADE } enum Rank { ACE, DEUCE, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING }... Collection suits = Arrays.asList(Suit.values()); Collection ranks = Arrays.asList(Rank.values()); List deck = new ArrayList (); for (Iterator i = suits.iterator(); i.hasNext(); ) for (Iterator j = ranks.iterator(); j.hasNext(); ) deck.add(new Card(i.next(), j.next()));  Solutions to prevent the bug  fix it in traditional way // Fixed, but ugly - you can do better! for (Iterator i = suits.iterator(); i.hasNext(); ) { Suit suit = i.next(); for (Iterator j = ranks.iterator(); j.hasNext(); ) deck.add(new Card(suit, j.next())); }  use for-each instead // Preferred idiom for nested iteration for (Suit suit : suits) for (Rank rank : ranks) deck.add(new Card(suit, rank));

Refer to objects by their interfaces  Interface oriented programming methodology  big advantage: much more flexible  sample case // Bad - uses class as type! Vector subscribers = new Vector (); // Good - uses interface as type List subscribers = new Vector (); // We can change subscribers to other List types easily List subscribers = new ArrayList ();  practical case in spring

Avoid float/double if exact answers required  Problems System.out.println( ); # output  Why it happens  binary floating-point arithmetic  float/double types are particularly illsuited for monetary calculations  Solutions to achieve exact computation  using java.math.BigDecimal BigDecimal bigDecimal = new BigDecimal("1.03"); System.out.println(bigDecimal.subtract(new BigDecimal(".42"))); # Tips -exact computation -performance impacted  using primitive arithmetic type: int or long -high performance -decimal point has to be handled manually

Prefer interfaces to reflection  What reflection can do Given a Class object, you can obtain Constructor, Method, and Field instances representing the constructors, methods, and fields of the class represented by the Class instance.  case study  initialize class instance via reflection Class cl = null; try { cl = Class.forName(args[0]); // Instantiate the class Set s = null; s = (Set ) cl.newInstance(); } catch(Exception e) {}  access class method/field via reflection Field f = cl.getClass().getDeclaredField(“f1"); f.setAccessible(true); Method m = f.getType().getDeclaredMethod(“f1m1", new Class[0]); m.setAccessible(true); m.invoke(cl, new Object[0]);

Prefer interfaces to reflection  cost on using reflection  no compile-time type checking  code clumsy and verbose  Performance suffers  When to use reflection  in runtime, better to use class instance normal access, unless necessary  base framework Spring Struts OSGI  dynamic class loading management

Prefer primitive types to boxed primitives  auto-boxing and auto-unboxing  since JDK1.5  sample  case study // Broken comparator - can you spot the flaw? Comparator naturalOrder = new Comparator () { public int compare(Integer first, Integer second) { return first < second ? -1 : (first == second ? 0 : 1); } }; Primitive typeReference type intjava.lang.Integer doublejava.lang.Double booleanjava.lang.Boolean

Prefer primitive types to boxed primitives(2)  fix the bug Comparator naturalOrder = new Comparator () { public int compare(Integer first, Integer second) { int f = first; // Auto-unboxing int s = second; // Auto-unboxing return f < s ? -1 : (f == s ? 0 : 1); // No unboxing } };  when you mix primitives and boxed primitives in a single operation, the boxed primitive is auto-unboxing public class Unbelievable { static Integer i; public static void main(String[] args) { if (i == 42) throws NullPointerException for Integer auto-unboxing System.out.println("Unbelievable"); }

Prefer primitive types to boxed primitives(3)  performance suffers during auto-boxing/unboxing // Hideously slow program! Can you spot the object creation? public static void main(String[] args) { Long sum = 0L; for (long i = 0; i < Integer.MAX_VALUE; i++) { sum += i; } System.out.println(sum); }  more practice tips  primitive types are simpler and faster  auto-boxing reduces the verbosity, but not the danger, of using boxed primitives  use boxed primitives as type parameter in in parameterized types // sample List l = new ArrayList (); ThreadLocal tl = new ThreadLocal ();

Avoid strings where other types are more appropriate  Strings are designed to represent text  poor substitutes for capabilities // Broken - inappropriate use of string as capability! public class ThreadLocal1 { private ThreadLocal1() { } // Non-instantiable // Sets the current thread's value for the named variable. public static void set(String key, Object value); // Returns the current thread's value for the named variable. public static Object get(String key); }  poor substitutes for enum types, hard to maintain public static enum UserRole { Admin, PM, BusinessOwner, Marketing, Finance, Legal }  poor substitutes for not text value types  Other

Other practical principles  Know and use the standard JDK libraries  By using a standard library, you take advantage of the knowledge of the experts who wrote it and the experience of those who used it before you.  java.lang, java.util, java.io  Use native methods judiciously  JNI: Java Native Interface  Platform dependent, less portable  Not safe, need anually memory control  Has a fixed cost associated with going into/out of native code  JVM gets faster, rarely advisable to use native method for performance gain  Optimize judiciously  write good program, architecture first, performance follows  avoid design decisions that limit performance  use profiling tools to determine performance optimization focus  Adhere to generally accepted naming conventions