0% found this document useful (0 votes)
48 views

Lecture01-Introduction and How To Write A Maintainable Code

The document outlines an advanced Java programming course, including: - Course details like writing maintainable code, debugging tools, J2EE, design patterns, and Java technologies. - Reading materials including textbooks and online references. - Grading policy based on assignments, exams, quizzes, and labs. - The objective is to learn best practices for enterprise Java programming and gain a practical understanding of design patterns.

Uploaded by

Aatif Kamal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Lecture01-Introduction and How To Write A Maintainable Code

The document outlines an advanced Java programming course, including: - Course details like writing maintainable code, debugging tools, J2EE, design patterns, and Java technologies. - Reading materials including textbooks and online references. - Grading policy based on assignments, exams, quizzes, and labs. - The objective is to learn best practices for enterprise Java programming and gain a practical understanding of design patterns.

Uploaded by

Aatif Kamal
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 60

Advanced Java Programming

Lecture-00-Course Outline
Aatif Kamal, Dept. of Computing [email protected]

Agenda

Course details Writing maintainable code

cs420

Fall 2011

Reading material

Text & Reference books

The Java EE 6 Tutorial


http://download.oracle.com/javaee/6/tutorial/doc/

Expert one-to-one J2EE Development without EJBs Wrox Publications, by Rod Johson Design Patterns Java Companion, By James W. Copper . Publisher Addison Wesley Introduction to Java Programming, Comprehensive, 8/E By Y. Daniel Liang Spring Recipes A Problem Solution Approach Pro JSF and Ajax Building Rich Internet Components Advanced Java 2 Platform, How to Program. By Deitel & Dietel. Pro Java Spring Patterns, By Dhrubojyoti Kayal, Publisher APress

Reference material

Selected publications available online on Moodle


cs420 Fall 2011

Course details

Lectures & Handouts

Will be available online Usually one (1) hour after the lecture

Office hours:

cs420

Fall 2011

Grading policy (Tentative)

Assignments

75% Theory Individual 30% Mid Exam No late submission 5%-10% Class Assignments Quizzes 20% Class Quizzes Mostly unannounced 45% -50% Final Exam Occasionally announced 25% Practical Most of the Lab 50% Lab Assignments assignments will be 50% Final Lab Exam + Viva marked as quiz after viva voice

cs420

Fall 2011

Objective of this course?

Programming ~ best practices


Writing maintainable/extensible code Methods of debugging, logging, profiling Design patterns J2EE Enterprise Application Development

Java Technologies

Outcomes

cs420

Fall 2011

Course outline
1.

How to write a maintainable/extensible code

2. 3. 4. 5. 6. 7. 8.
1. 2. 3. 4.

Concept of Reflection Code debugging, Logging & Profiling tools (log4J) J2EE Overview & Web Application Architecture Servlets, JSP and Beans in detail Tags & JSTL Hibernate Spring Framework Core
Presentation Tier Design Patterns Business Tier Design Patterns Integration Tier Design Patterns Crosscutting Tier Design Patterns

9.

Java Server Faces


cs420 Fall 2011

Expectations from the course


Learn Enterprise JAVA Programming
Its serious programming Relies on proven best practices & techniques Good practical understanding of Design Patterns is the key AOP, IOC (Inversion of control), MVC2 etc

My expectation from the class


At least 10 hours per week of home study Programming & Programming & Programming Take this course very seriously, this an Advance course of programming taught in last year of you degree
cs420 Fall 2011

Lets begin!

Ref: csc.liv.ac.uk

What is maintainable/extensible code?

Second most important attribute

A programmer should be able to understand it when reading it for the first time

Most important attribute

It should work!

10

cs420

Fall 2011

Why do we write un-maintainable code?


Article: The Rise of ``Worse is Better''
http://www.jwz.org/doc/worse-is-better.html

Laziness Use all the tools in the box Inexperience ~ havent extended a program Indifference ~ Elitism

My method is the best Job security

Others should not be able to understand!

11 cs420 Fall 2011

Why should we write maintainable code?

Clear code almost always results in reliable code (functionality & security)
except for very rare instances, the lifetime cost of code written to be maintainable from the start will always be less than the cost of code written with little of no thought to maintainability http://www.svalli.com/book.html

12

cs420

Fall 2011

What to do?

Documentation

Too little - too much


Useful comments Keep your comments short Spell check

How serious one is about comments

If there are questions about the code, comments need to be improved

14

cs420

Fall 2011

Code formatting

Use consistent formatting


Tabs vs Spaces

Always use spaces Set your IDE to replace TABS with spaces

Follow the convention

15

cs420

Fall 2011

Java Programming Style

Remember!!!
Any violation of the convention is allowed if it enhances readability

Naming

Packages should always be named in small letters

mypackage, com.company.application.ui

Names representing types must be nouns and written in mixed case starting with upper case

Line, AudioSystem

Variable names must be in mixed case starting with lower case

line, audioSystem

18

cs420

Fall 2011

Naming

Names representing constants (final variables) must be all uppercase using underscore to separate words

MAX_ITERATIONS, COLOR_RED

In general, the use of such constants should be minimized. In many cases implementing the value as a method is a better choice:

int getMaxIterations(){ return 25; } // NOT: MAX_ITERATIONS = 25

19

cs420

Fall 2011

Naming

Names representing methods must be verbs and written in mixed case starting with lower case

getName(), computeTotalWidth()

Abbreviations and acronyms should not be uppercase when used as name

exportHtmlSource(); // NOT: exportHTMLSource(); openDvdPlayer(); // NOT: openDVDPlayer();


cs420 Fall 2011

20

Naming

Private class variables should have underscore suffix

private String name_;

A side effect of the underscore naming convention is that it nicely resolves the problem of finding reasonable variable names for setter methods:
void setName(String name) { name_ = name; }

21

cs420

Fall 2011

Naming Generic variables should have the same name as their type

void setTopic(Topic topic) // NOT: void setTopic(Topic value) // NOT: void setTopic(Topic aTopic) // NOT: void setTopic(Topic t) void connect(Database database) // NOT: void connect(Database db) // NOT: void connect(Database oracleDB)

All names should be written in English Variables with a large scope should have long names, variables with a small scope can have short names

22 cs420 Fall 2011

Naming

The name of the object is implicit, and should be avoided in a method name

line.getLength(); // NOT: line.getLineLength();

23

cs420

Fall 2011

Specific Naming Conventions

The terms get/set must be used where an attribute is accessed directly

employee.getName(); employee.setName(name); matrix.getElement(2, 4); matrix.setElement(2, 4, value);

is prefix should be used for boolean variables and methods (has, can and should prefixes)

isSet, isVisible, isFinished, isFound, isOpen boolean canEvaluate(); boolean shouldAbort = false;

24

cs420

Fall 2011

Specific Naming Conventions

The term compute, find, initialize


valueSet.computeAverage(); matrix.computeInverse(); vertex.findNearestVertex(); matrix.findSmallestElement(); printer.initializeFontSet();

JFC (Java Swing) variables should be suffixed by the element type

widthScale, nameTextField, leftScrollbar, mainPanel, fileToggle, minLabel, printerDialog

Plural form should be used on names representing a collection of objects

int[] values;
cs420 Fall 2011

25

Specific Naming Conventions

n prefix should be used for variables representing a number of objects

nPoints, nLines

No suffix should be used for variables representing an entity number (An elegant alternative is to prefix such variables with an I. This effectively makes them named iterators )

tableNo, employeeNo iTable, iEmployee

26

cs420

Fall 2011

Specific Naming Conventions

Iterator variables should be called i, j, k etc

for (Iterator i = points.iterator(); i.hasNext(); ) { : }

Variables named j, k etc. should be used for nested loops only. Abbreviations in names should be avoided

computeAverage(); // NOT: compAvg(); ActionEvent event; // NOT: ActionEvent e;

Negated boolean variable names must be avoided

bool isError; // NOT: isNoError

27

cs420

Fall 2011

Specific Naming Conventions

Associated constants (final variables) should be prefixed by a common type name


final int COLOR_RED = 1; final int COLOR_GREEN = 2; interface Color { final int RED = 1; final int GREEN = 2; final int BLUE = 3; }

Exception classes should be suffixed with Exception

class AccessException extends Exception { : }

28

cs420

Fall 2011

Specific Naming Conventions

Singleton classes should return their sole instance through method getInstance

class UnitManager { private final static UnitManager instance_ = new UnitManager(); private UnitManager() { ... } public static UnitManager getInstance() // NOT: get() or instance() or unitManager() etc.{ return instance_; } }

29

cs420

Fall 2011

Specific Naming Conventions

Classes that creates instances on behalf of others (factories) can do so through method new[ClassName]

class PointFactory { public Point newPoint(...) { ... } }

Functions (methods returning an object) should be named after what they return and procedures (void methods) after what they do

30

cs420

Fall 2011

Files

Java source files should have the extension .java Classes should be declared in individual files with the file name matching the class name.

Secondary private classes can be declared as inner classes and reside in the file of the class they belong to

File content must be kept within 80 columns Special characters like TAB and page break must be avoided

31

cs420

Fall 2011

Files

The incompleteness of split lines must be made obvious


totalSum = a + b + c + d + e; method(param1, param2, param3);

Break after a comma. Break after an operator. Align the new line with the beginning of the expression on the previous line

32

cs420

Fall 2011

Package and Import Statements

The package statement must be the first statement of the file. All files should belong to a specific package. The import statements must follow the package statement. import statements should be sorted with the most fundamental packages first, and grouped with associated packages together and one blank line between groups.

import java.io.IOException; import java.net.URL; import java.rmi.RmiServer; import java.rmi.server.Server; import org.linux.apache.server.SoapServer;

33

cs420

Fall 2011

Package and Import Statements

Imported classes should always be listed explicitly

import java.util.List; // NOT: import java.util.*; import java.util.ArrayList; import java.util.HashSet;

34

cs420

Fall 2011

Classes and Interfaces

Class and Interface declarations should be organized in the following manner


1.
2.

3.
4. 5. 6.

Class/Interface documentation. class or interface statement. Class (static) variables in the order public, protected, package (no access modifier), private. Instance variables in the order public, protected, package (no access modifier), private. Constructors. Methods (no specific order).

35

cs420

Fall 2011

Methods

Method modifiers should be given in the following order: <access> static abstract synchronized <unusual> final native The <access> modifier (if present) must be the first modifier

public static double square(double a); // NOT: static public double square(double a);

36

cs420

Fall 2011

Types

Type conversions must always be done explicitly. Never rely on implicit type conversion.

floatValue = (int) intValue; // NOT: floatValue = intValue;

Array specifiers must be attached to the type not the variable

int[] a = new int[20]; // NOT: int a[] = new int[20]

37

cs420

Fall 2011

Variables

Variables should be initialized where they are declared

and they should be declared in the smallest scope possible

Variables must never have dual meaning Class variables should never be declared public Variables should be kept alive for as short a time as possible

38

cs420

Fall 2011

Loops

Only loop control statements must be included in the for() construction

sum = 0; for (i = 0; i < 100; i++) sum += value[i]; // NOT: for (i = 0, sum = 0; i < 100; i++) // sum += value[i];

39

cs420

Fall 2011

Loops

Loop variables should be initialized immediately before the loop

isDone = false; // NOT: bool isDone = false; while (!isDone) { // : : // while (!isDone) { } // : // }

The use of do-while loops can be avoided The use of break and continue in loops should be avoided

40

cs420

Fall 2011

Conditionals

Complex conditional expressions must be avoided. Introduce temporary boolean variables instead

bool isFinished = (elementNo < 0) || (elementNo > maxElement); bool isRepeatedEntry = elementNo == lastElement; if (isFinished || isRepeatedEntry) { : } // NOT: if ((elementNo < 0) || (elementNo > maxElement)|| elementNo == lastElement) { : }

41

cs420

Fall 2011

Conditionals

The nominal case should be put in the if-part and the exception in the else-part of an if statement

boolean isOk = readFile(fileName); if (isOk) { : } else { : }

The conditional should be put on a separate line

if (isDone) doCleanup();

// NOT: if (isDone) doCleanup();

42

cs420

Fall 2011

Conditionals

Executable statements in conditionals must be avoided

InputStream stream = File.open(fileName, "w"); if (stream != null) { : } // NOT: if (File.open(fileName, "w") != null)) { : }

43

cs420

Fall 2011

Miscellaneous

The use of magic numbers in the code should be avoided. Numbers other than 0 and 1 can be considered declared as named constants instead

private static final int TEAM_SIZE = 11; : Player[] players = new Player[TEAM_SIZE]; // NOT: Player[] players = new Player[11];

44

cs420

Fall 2011

Miscellaneous

Floating point constants should always be written with decimal point and at least one decimal

double total = 0.0; // NOT: double total = 0; double speed = 3.0e8; // NOT: double speed = 3e8; double sum; : sum = (a + b) * 10.0;

45

cs420

Fall 2011

Miscellaneous

Floating point constants should always be written with a digit before the decimal point.

double total = 0.5; // NOT: double total = .5;

Static variables or methods must always be refered to through the class name and never through an instance variable.

Thread.sleep(1000); // NOT: thread.sleep(1000);

46

cs420

Fall 2011

Layout and Comments

Basic indentation should be 2.

for (i = 0; i < nElements; i++) a[i] = 0; while (!done) { doSomething(); done = moreToDo(); } while (!done) { doSomething(); done = moreToDo(); }

47

cs420

Fall 2011

Layout and Comments

The class and interface declarations should have the following form

class Rectangle extends Shape implements Cloneable, Serializable { ... }

Method definitions should have the following form

public void someMethod() throws SomeException { ... }

48

cs420

Fall 2011

Layout and Comments

The if-else class of statements should have the following form

if (condition) { statements; } else { statements; }

An empty for statement should have the following form

for (initialization; condition; update) { statements; }

49

cs420

Fall 2011

Layout & Comments

while
do while switch try catch

single if else

50

cs420

Fall 2011

White Spaces

Operators should be surrounded by a space character. Java reserved words should be followed by a white space. Commas should be followed by a white space. Colons should be surrounded by white space. Semicolons in for statements should be followed by a space character. Method names can be followed by a white space when it is followed by another name

// Create a new identity matrix Matrix4x4 matrix = new Matrix4x4(); // Precompute angles for efficiency double cosAngle = Math.cos(angle); double sinAngle = Math.sin(angle);

51

cs420

Fall 2011

White Spaces

Variables in declarations can be left aligned

TextFile int double

file; nPoints; x, y;

Statements should be aligned wherever this enhances readability

if (a == lowValue) compueSomething(); else if (a == mediumValue) computeSomethingElse(); else if (a == highValue) computeSomethingElseYet();

52

cs420

Fall 2011

Comments

Tricky code should not be commented but rewritten All comments should be written in English

53

cs420

Fall 2011

Comments

Javadoc comments should have the following form

/** * Return lateral location of the specified position. * If the position is unset, NaN is returned. * * @param x X coordinate of position. * @param y Y coordinate of position. * @param zone Zone of position. * @return Lateral location. * @throws IllegalArgumentException If zone is <= 0. */ public double computeLocation(double x, double y, int zone) throws IllegalArgumentException { ... }

54

cs420

Fall 2011

Comments

Javadoc of class members can be specified on a single line as follows:

/** Number of connections to this database */ private int nConnections_;

There should be a space after the comment identifier.

// This is a comment NOT: //This is a comment /** NOT: /** * This is a javadoc *This is a javadoc * comment *comment */ */

55

cs420

Fall 2011

Comments

Use // for all non-JavaDoc comments, including multi-line comments.

// Comment spanning // more than one line

Comments should be indented relative to their position in the code

while (true) { // Do something something();

// NOT: while (true) { // Do something something();

56

cs420

Fall 2011

Comments

All public classes and public and protected functions within public classes should be documented using the Java documentation (javadoc) conventions.

57

cs420

Fall 2011

Summary

Write clean code


Reduces development cost Easy to understand and extend/maintain Simple implementations are usually optimal Makes your life easy Makes the readers life easy

58

cs420

Fall 2011

Assignment 01

Write a file sharing application. User can send zip file (upto 50 MB) from one machine to another User can select any of two protocols (UDP or TCP). i.e. implement both of these Proper desktop swing Interface for file selection Create two folders incoming & outgoing File to be sent must first be copied to outgoing folder of sender File received must be placed in incoming folder Bonus marks

User can select more then one file or folder, application first create a Zip file & then unzip the files on receiver side Progress bar to show the progress of upload and download
Successfully unzip the file on user side.

Test Case

Read Creational Patterns

Factory Pattern, Abstract Factory Pattern Singlton Pattern


cs420 Fall 2011

59

Questions?
Thats all for today!

You might also like