advanced programming

Post on 01-Jan-2016

23 Views

Category:

Documents

5 Downloads

Preview:

Click to see full reader

DESCRIPTION

Advanced Programming. Rabie A. Ramadan rabieramadan@gmail.com http://www.rabieramadan.org/classes/2014/AdvPro/ Lecture 1. Welcome Back. Attendance is very important Assignments Projects Quizzes. Class Organization. Textbooks. Object Serialization Advanced I/O - New I/O Reflection - PowerPoint PPT Presentation

TRANSCRIPT

Advanced Programming

Rabie A. Ramadanrabieramadan@gmail.com

http://www.rabieramadan.org/classes/2014/AdvPro/

Lecture 1

2

Welcome Back

Class Organization

3

Attendance is very important Assignments Projects Quizzes

Textbooks

4

Topics to be Covered

5

Object Serialization Advanced I/O - New I/O Reflection Advanced JDBC Networking with Sockets Remote Method Invocation Keys, Signatures, and Certificates Java Authentication and Authorization Service (JAAS) Parsing XML with Java - JAXP Java Design Patterns Effective Java topics

Class Format

6

Some presentations by myself

Presentations by you

Report discussion biweekly

Labs

Grading

7

Midterm grades will be added towards the project

Labs

Assignments

Agenda

8

Introduction and Course Motivation

Project

Assignment 1 – Get your hands dirty

Introduction and Course Motivation

9

Computer Programming is the art of making a computer do what you want it to do.

Terminology

API – Application Programming Interface• Classes, Interfaces, Constructors, Members, and

Serialized Forms By Which a Programmer Accesses a Class, Interface, or Package

User• A Programmer Who Writes a Program That Uses an API

Client• A Class Whose Implementation Uses an API

Key Principles For Using Any Language

Focus on Clarity and Simplicity Don’t Surprise Users of an API

• Hide Complexity Underneath, Not In, The API Reuse Rather Than Copy Minimize Dependencies Between Modules

• Some Early Habits Need to Be Broken Detect Errors As Soon As Possible

• Compile-Time Detection Beats Run-Time Failure

• Run-Time Exceptions Beat Undefined Behavior

Performance

Bloch Does not Focus on Performance• Instead, Strive to Write Programs that are:

• Clear, Correct, Robust, Flexible, Maintainable

Start With Sound Software Engineering• Get Performance Later Where You Need It

Excessive Performance Focus Has Real Costs• Think About Why a Language Like C++ is so Complex

Who are You ?

13

Just a coder • Most of us are coders not programmers

Programmer / Developer• Writes an efficient code

Project

14

Project

Assignment 1

15

Available on the website

Some Salient Characteristics of Java

16

Java is platform independent: the same program can run on any correctly implemented Java system

Java is object-oriented:

• Structured in terms of classes, which group data with operations on that data

• Can construct new classes by extending existing ones Java designed as

• A core language plus

• A rich collection of commonly available packages Java can be embedded in Web pages

Java Processing and Execution

Appendix A: Introduction to Java 17

Begin with Java source code in text files: Model.java A Java source code compiler produces Java byte code

• Outputs one file per class: Model.class

• May be standalone or part of an IDE

A Java Virtual Machine loads and executes class files

• May compile them to native code (e.g., x86) internally

Compiling and Executing a Java Program

Appendix A: Introduction to Java 18

Java: Write Once, Run Anywhere

Consequence of Java’s history: platform-independence

Mac user running Safari

Windows user running Internet Explorer

Web page stored on Unix server

Click on link to Applet

Byte code is downloaded

Virtual machine translates byte code to

native Mac code and the Applet is run

Byte code (part of web page)

Java: Write Once, Run Anywhere

Consequence of Java’s history: platform-independent

Mac user running Safari

Windows user running Internet Explorer

Web page stored on Unix server

Click on link to AppletByte code is downloaded

Virtual machine translates byte code to

native Windows code and the Applet is run

Java: Write Once, Run Anywhere (2)

But Java can also create standard (non-web based) programs

Dungeon Master (Java version) http://homepage.mac.com/aberfield/dmj/

Examples of mobile Java games: http://www.mobilegamesarena.net

Kung Fu Panda 2: THQ

Java: Write Once, Run Anywhere (3) Java has been used by large and reputable companies to

create serious stand-alone applications. Example:

• Eclipse1: started as a programming environment created by IBM for developing Java programs. The program Eclipse was itself written in Java.

1 For more information: http://www.eclipse.org/downloads/

Compiled Programs With Different Operating Systems

Windows compiler

Executable (Windows)

UNIX compiler

Executable (UNIX)

Mac OS compiler

Executable (Mac)

Computer program

A High Level View Of Translating/Executing Java Programs

Java compiler (javac)

Java program

Filename.java

Java bytecode (generic binary)

Filename.class

Stage 1: Compilation

A High Level View Of Translating/Executing Java Programs (2)

Java interpreter (java)

Java bytecode (generic binary)

Filename.class

Machine language instruction (UNIX)

Machine language instruction (Windows)

Machine language instruction (Apple)

Stage 2: Interpreting and executing the byte code

Classes and Objects

Appendix A: Introduction to Java 26

The class is the unit of programming A Java program is a collection of classes

• Each class definition (usually) in its own .java file

• The file name must match the class name A class describes objects (instances)

• Describes their common characteristics: is a blueprint

• Thus all the instances have these same characteristics These characteristics are:

• Data fields for each object

• Methods (operations) that do work on the objects

Grouping Classes: The Java API

27

API = Application Programming Interface Java = small core + extensive collection of packages A package consists of some related Java classes:

• Swing: a GUI (graphical user interface) package

• AWT: Application Window Toolkit (more GUI)

• util: utility data structures The import statement tells the compiler to make available

classes and methods of another package A main method indicates where to begin executing a class (if it

is designed to be run as a program)

A Little Example of import and main

28

import javax.swing.*;

// all classes from javax.swing

public class HelloWorld { // starts a class

public static void main (String[] args) {

// starts a main method

// in: array of String; out: none (void)

}

} public = can be seen from any package static = not “part of” an object

Processing and Running HelloWorld

29

javac HelloWorld.java• Produces HelloWorld.class (byte code)

java HelloWorld• Starts the JVM and runs the main method

References and Primitive Data Types

30

Java distinguishes two kinds of entities• Primitive types

• Objects

Primitive-type data is stored in primitive-type variables

Reference variables store the address of an object

Primitive Data Types

31

Represent numbers, characters, boolean values

Integers: byte, short, int, and long Real numbers: float and double Characters: char

Primitive Data Types

Data type Range of values

byte -128 .. 127 (8 bits)

short -32,768 .. 32,767 (16 bits)

int -2,147,483,648 .. 2,147,483,647 (32 bits)

long -9,223,372,036,854,775,808 .. ... (64 bits)

float +/-10-38 to +/-10+38 and 0, about 6 digits precision

double +/-10-308 to +/-10+308 and 0, about 15 digits precision

char Unicode characters (generally 16 bits per char)

boolean True or false

32

Operators

33

1. subscript [ ], call ( ), member access .2. pre/post-increment ++ --, boolean complement !, bitwise

complement ~, unary + -, type cast (type), object creation new

3. * / %4. binary + - (+ also concatenates strings)5. signed shift << >>, unsigned shift >>>6. comparison < <= > >=, class test instanceof7. equality comparison == !=8. bitwise and &9. bitwise or |

Operators

34

11. logical (sequential) and &&

12. logical (sequential) or ||

13. conditional cond ? true-expr : false-expr

14. assignment =, compound assignment += -= *= /= <<= >>= >>>= &= |=

Type Compatibility and Conversion

35

Widening conversion:

• In operations on mixed-type operands, the numeric type of the smaller range is converted to the numeric type of the larger range

• In an assignment, a numeric type of smaller range can be assigned to a numeric type of larger range

byte to short to int to long int kind to float to double

Declaring and Setting Variables

36

int square;

square = n * n;double cube = n * (double)square;• Can generally declare local variables where

they are initialized

• All variables get a safe initial value anyway (zero/null)

Java Control Statements

37

A group of statements executed in order is written•{ stmt1; stmt2; ...; stmtN; }

The statements execute in the order 1, 2, ..., N

Java Control Statements (continued)

Appendix A: Introduction to Java 38

Java Control Statements (continued)

39

Methods

40

A Java method defines a group of statements as performing a particular operation

static indicates a static or class method A method that is not static is an instance method All method arguments are call-by-value

• Primitive type: value is passed to the method

• Method may modify local copy but will not affect caller’s value

• Object reference: address of object is passed

• Change to reference variable does not affect caller

• But operations can affect the object, visible to caller

The String Class

Appendix A: Introduction to Java 41

The String class defines a data type that is used to store a sequence of characters

You cannot modify a String object

• If you attempt to do so, Java will create a new object that contains the modified character sequence

Comparing Objects

42

You can’t use the relational or equality operators to compare the values stored in strings (or other objects)

(You will compare the pointers, not the objects!)

The StringBuffer Class

Appendix A: Introduction to Java 43

Stores character sequences Unlike a String object, you can change

the contents of a StringBuffer object

StringTokenizer Class

44

We often need to process individual pieces, or tokens, of a String

Arrays

45

In Java, an array is also an object The elements are indexes and are referenced using the form

arrayvar[subscript]

Array Example

46

float grades[] = new float[numStudents];

... grades[student] = something; ...

float total = 0.0;

for (int i = 0; i < grades.length; ++i) {

total += grades[i];

}

System.out.printf(“Average = %6.2f%n”,

total / numStudents);

Array Example Variations

47

// possibly more efficient

for (int i = grades.length; --i >= 0; ) {

total += grades[i];

}

// uses Java 5.0 “for each” looping

for (float grade : grades) {

total += grade;

}

Input/Output using Streams

48

An InputStream is a sequence of characters representing program input data

An OutputStream is a sequence of characters representing program output

The console keyboard stream is System.in The console window is associated with System.out

Opening and Using Files: Reading Input

49

import java.io.*;

public static void main (String[] args) {

// open an input stream (**exceptions!)

BufferedReader rdr =

new BufferedReader(

new FileReader(args[0]));

// read a line of input

String line = rdr.readLine();

// see if at end of file

if (line == null) { ... }

Item 1: Consider Static Factory Methods Instead of Constructors

Factory methods: • Have names, unlike constructors, which can clarify code.

• Do not need to create a new object upon each invocation - objects can be cached and reused, if necessary.

• Can return a subtype of their return type - in particular, can return an object whose implementation class is unknown to the caller.

Item 1: Consider Static Factory Methods Instead of Constructors

Constructor Calls vs Static Factory Method

Item 1: Advantages

Unlike constructors, static factory methods • Can have meaningful names

• Need not create new instances

• Can return any subtype of return type• Reduces client dependency on specific class

• Can reduce verbosity of creating parameterized type instances

Advantage 2: Not Required To Create New Object

Instance-controlled classes can be useful• Can avoid creating unnecessary duplicate objects

• Boolean.valueOf(boolean) is an example

• Can guarantee a “singleton” or “noninstatiable” object

• Can allow for very fast “equals” test

Advantage 3: Can Return Subtype of Return Type

Consider the java.util.Collections class• 32 Convenience implementations of Collection interfaces

• All are static factory methods

• Interface return type vs. actual classes Static factory methods can hide multiple

implementations•java.util.EnumSet has two implementations

• Future release could easily change this

• Clients neither know nor care about actual type

• Reduce client dependencies!

Advantage 4: Reduce Verbosity of Parameterized Type Instances

// Parameterized type instancesMap<String, List<String>> m = new HashMap<String, List<String>>();

vs.

// Static factory alternative

public static <K, V> HashMap<K, V> newInstance() { return new HashMap<K, V>();}

// Now, client code looks like this// Compiler does type inference!

Map<String, List<String>> m = HashMap.newInstance();

Item 1: Disadvantages of Static Factory Methods

Naming conventions necessary•valueOf – effectively a type converter (also just of)

•getInstance – return instance described by parameters

•newInstance – like getInstance, but guarantees distinct object

•getType – like getInstance, but converts type

•newType – like newInstance, but converts type

Item 3: Enforce Singleton Property

A Singleton is a class that’s instantiated exactly once• Note: singletons are hard to mock in unit testing

Two approaches before Enums:• Public static member (a constant, of course)

• Public static factory method

Enum singleton is now preferred• Lots of subtle advantages: security, serialization, etc.

Item 3: Code Example

// Option 1: public final field// Option 1: public final fieldpublic class Elvis { public static final Elvis INSTANCE = new Elvis(); private Elvis() {...}}

// Option 2: static factory method// Option 2: static factory methodpublic class Elvis { private static final Elvis INSTANCE = new Elvis(); private Elvis() {...} public static Elvis getInstance() { return INSTANCE; }}

// Option 3: Enum type – now the preferred approach// Option 3: Enum type – now the preferred approachpublic enum Elvis { INSTANCE; ...}

Item 4: Enforce Noninstantiability With a Private Constructor

Some classes just group static methods and/or fields• Makes no sense to instantiate such a class

Trying to enforce noninstantiability by making class abstract doesn’t work• Subclassing is possible

• Clients are led to believe subclassing makes sense However, a private constructor does the job

Item 4: Code Example

// Noninstantiable utility classpublic class UtilityClass { // Suppress default constructor for noninstantiability

private UtilityClass() {private UtilityClass() {

throw new AssertionError();throw new AssertionError();

}} ... // Remainder of class omitted}

// Note that no subclassing is possible (constructor chaining...)// Note that client can’t call constructor// Note that if constructor is mistakenly called inside class,// there is an immediate assertion violation.

Item 5: Avoid Creating Unnecessary Objects

On the one hand, performance is a secondary concern behind correctness

On the other, gratuitous object creation is just bad programming

// String s = new String(“stringette”); // Don’t do this!

vs.

// String s = “stringette”; // Let JVM optimize for you

// Also see earlier Boolean.valueOf() static factory example

Item 5: Code Example

public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted // DON’T DO THISpublic boolean isBabyBoomer() { // Unnecessary allocation of expensive object Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”)); gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomStart = gmtCal.getTime(); gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0); Date boomEnd = gmtCal.getTime(); return birthDate.compareTo(boomStart) >= 0 && birthDate.compareTo(boomEnd) < 0; }}

Item 5: Code Example Fixed

public class Person { private final Date birthDate; // Other fields, methods, and constructor omitted private static final Date BOOM_START; private static final Date BOOM_END; static { // Note static blockstatic { // Note static block

Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”));Calendar gmtCal = Calendar.getInstance(TimeZone.getTimeZone(“GMT”));

gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0);gmtCal.set(1946, Calendar.JANUARY, 1, 0, 0, 0, 0);

BOOM_START = gmtCal.getTime(); BOOM_START = gmtCal.getTime();

gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0);gmtCal.set(1965, Calendar.JANUARY, 1, 0, 0, 0, 0);

BOOM_END = gmtCal.getTime();BOOM_END = gmtCal.getTime();

}}

public boolean isBabyBoomer() {public boolean isBabyBoomer() {

return birthDate.compareTo(BOOM_START) >= 0 &&return birthDate.compareTo(BOOM_START) >= 0 &&

birthDate.compareTo(BOOM_END) < 0;birthDate.compareTo(BOOM_END) < 0;

}}}

Item 5: Autoboxing Overhead

// 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);}

// Lessons: 1) prefer primitives to Boxed primitives// 2) watch for unintentional autoboxing// why are you using classes where there is no need for them?

Item 6: Eliminate Obsolete Object References

Sometimes, you manage your own memory (leak)• Example: Stack.javapublic Object pop () {

if (size == 0) throw new IllegalStateException("Stack.pop");

Object result = elements[--size];

elements[size] = null; // Eliminate obsolete reference

return result;

}

Also a problem with caches and registration of listeners and callbacks• Suggestion: Use weak pointers, such as WeakHashMap

Item 7: Avoid Finalizers

finalize() is a method in the Object class• What the garbage collector may call when cleaning up an

unused object Finalizers: unpredictable, dangerous, unnecessary!

• They are NOT the analog of C++ destructors There is no guarantee a finalizer will ever be called Finalizers have severe performance penalties Instead, provide explicit termination methods

• Sometimes requires “finalizer chaining”

Item 7: Code Example

// try-finally block guarantees execution of termination method

// termination method ensures resources are released// Example resources: database connections, threads, windowsFoo foo = new Foo();try { // Do what must be done with foo} finally { foo.terminate(); // Explicit termination method in Foo}

Item 7: Finalizer chaining// Manual finalizer chaining// Only do this if you *have* to use the finalizer@Override protected void finalize() throws Throwable { try { .. . // Finalize subclass state } finally super.finalize(); // Note order of finalizer

chaining }}

top related