Upload
aatif-kamal
View
223
Download
0
Embed Size (px)
Citation preview
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
1/60
Advanced Java Programming
Lecture-00-Course Outline
Aatif Kamal, Dept. of [email protected]
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
2/60
Agenda
Fall 2011cs4202
Course details Writing maintainable code
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
3/60
Reading material
Fall 2011cs4203
Text & Reference books The Java EE 6 Tutorial
http://download.oracle.com/javaee/6/tutorial/doc/
Expert one-to-one J2EE Development without EJBsWrox 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
http://download.oracle.com/javaee/6/tutorial/doc/http://download.oracle.com/javaee/6/tutorial/doc/8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
4/60
Course details
Fall 2011cs4204
Lectures & Handouts Will be available online
Office hours:
Usually one (1) hour after the lecture
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
5/60
Grading policy (Tentative)
Fall 2011cs4205
75% Theory
30% Mid Exam5%-10% Class Assignments20% Class Quizzes
45% -50% Final Exam25% Practical
50% Lab Assignments50% Final Lab Exam + Viva
voice
Assignments Individual
No late submission
Quizzes Mostly unannounced
Occasionally announced
Most of the Labassignments will bemarked as quiz after viva
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
6/60
Objective of this course?
Fall 2011cs4206
Programming ~ best practices
Writing maintainable/extensible code
Methods of debugging, logging, profiling
Design patterns
Java Technologies
J2EE
Outcomes
Enterprise Application Development
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
7/60
Course outline
Fall 2011cs4207
1. How to write a maintainable/extensible code
2. Concept of Reflection3. Code debugging, Logging & Profiling tools (log4J)4. J2EE Overview & Web Application Architecture5. Servlets, JSP and Beans in detail
6. Tags & JSTL7. Hibernate
8. Spring Framework Core1. Presentation Tier Design Patterns2. Business Tier Design Patterns
3. Integration Tier Design Patterns4. Crosscutting Tier Design Patterns
9. Java Server Faces
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
8/60
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
Fall 2011cs420
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
9/60
Lets begin!
Ref: csc.liv.ac.uk
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
10/60
What is maintainable/extensible
code?
Fall 2011cs42010
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!
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
11/60
Why do we write un-maintainable
code?
Fall 2011cs42011
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
Others should not be able to understand! Job security
http://www.jwz.org/doc/worse-is-better.htmlhttp://www.jwz.org/doc/worse-is-better.htmlhttp://www.jwz.org/doc/worse-is-better.htmlhttp://www.jwz.org/doc/worse-is-better.htmlhttp://www.jwz.org/doc/worse-is-better.htmlhttp://www.jwz.org/doc/worse-is-better.htmlhttp://www.jwz.org/doc/worse-is-better.html8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
12/60
Why should we write maintainable
code?
Fall 2011cs42012
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 willalways be less than the cost of code written with littleof no thought to maintainability
http://www.svalli.com/book.html
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
13/60
What to do?
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
14/60
Documentation
Fall 2011cs42014
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, commentsneed to be improved
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
15/60
Code formatting
Fall 2011cs42015
Use consistent formatting
Tabs vs Spaces
Always use spaces
Set your IDE to replace TABS with spaces
Follow the convention
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
16/60
Java Programming Style
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
17/60
Remember!!!
Any violation of the convention is allowed if
it enhances readability
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
18/60
Naming
Fall 2011cs42018
Packages should always be named in smallletters 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 startingwith lower case line, audioSystem
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
19/60
Naming
Fall 2011cs42019
Names representing constants (final variables)must be all uppercase using underscore toseparate words MAX_ITERATIONS, COLOR_RED
In general, the use of such constants should beminimized. In many cases implementing thevalue as a method is a better choice: int getMaxIterations(){ return 25; }
// NOT: MAX_ITERATIONS = 25
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
20/60
Naming
Fall 2011cs42020
Names representing methods must beverbs and written in mixed case startingwith lower case
getName(), computeTotalWidth()
Abbreviations and acronyms should not beuppercase when used as name exportHtmlSource();
// NOT: exportHTMLSource();openDvdPlayer();
// NOT: openDVDPlayer();
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
21/60
Naming
Fall 2011cs42021
Private class variables should haveunderscore suffix private String name_;
A side effect of the underscore namingconvention is that it nicely resolves theproblem of finding reasonable variablenames for setter methods:
void setName(String name){ name_ = name; }
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
22/60
Naming
Fall 2011cs42022
Generic variables should have the samename 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 havelong names, variables with a small scopecan have short names
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
23/60
Naming
Fall 2011cs42023
The name of the object is implicit, and should beavoided in a method name
line.getLength(); // NOT: line.getLineLength();
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
24/60
Specific Naming Conventions
Fall 2011cs42024
The terms get/setmust be used where anattribute is accessed directly employee.getName();
employee.setName(name);
matrix.getElement(2, 4);matrix.setElement(2, 4, value);
isprefix should be used for boolean variablesand methods (has, canand shouldprefixes)
isSet, isVisible, isFinished, isFound, isOpenboolean canEvaluate();
boolean shouldAbort = false;
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
25/60
Specific Naming Conventions
Fall 2011cs42025
The term compute, find, initialize valueSet.computeAverage();matrix.computeInverse();
vertex.findNearestVertex();matrix.findSmallestElement();
printer.initializeFontSet();
JFC (Java Swing) variables should be suffixed bythe element type widthScale, nameTextField, leftScrollbar, mainPanel,
fileToggle, minLabel, printerDialog
Plural form should be used on namesrepresenting a collection of objects int[] values;
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
26/60
Specific Naming Conventions
Fall 2011cs42026
nprefix should be used for variablesrepresenting a number of objects
nPoints, nLines
Nosuffix should be used for variables
representing an entity number (An elegant alternative is to prefix such variables
with an I. This effectively makes them namediterators ) tableNo, employeeNo
iTable, iEmployee
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
27/60
Specific Naming Conventions
Fall 2011cs42027
Iterator variables should be called i,j, ketc for (Iterator i = points.iterator();
i.hasNext(); ) { : }
Variables namedj, ketc. should be used fornested 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
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
28/60
Specific Naming Conventions
Fall 2011cs42028
Associated constants (final variables) should beprefixed 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 { : }
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
29/60
Specific Naming Conventions
Fall 2011cs42029
Singleton classes should return their sole instancethrough 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_;
}
}
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
30/60
Specific Naming Conventions
Fall 2011cs42030
Classes that creates instances on behalf of others(factories) can do so through methodnew[ClassName] class PointFactory {
public Point newPoint(...) { ... }
}
Functions (methods returning an object) should benamed after what they return and procedures (voidmethods) after what they do
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
31/60
Files
Fall 2011cs42031
Java source files should have the extension .java
Classes should be declared in individual files withthe 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 beavoided
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
32/60
Files
Fall 2011cs42032
The incompleteness of split lines must be madeobvious 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
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
33/60
Package and Import Statements
Fall 2011cs42033
Thepackage statement must be the first statementof the file. All files should belong to a specific
package.
The import statements must follow the packagestatement. import statements should be sortedwith the most fundamental packages first, andgrouped with associated packages together andone 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;
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
34/60
Package and Import Statements
Fall 2011cs42034
Imported classes should always be listed explicitly import java.util.List; // NOT: import java.util.*;
import java.util.ArrayList;
import java.util.HashSet;
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
35/60
Classes and Interfaces
Fall 2011cs42035
Class and Interface declarations should beorganized in the following manner
1. Class/Interface documentation.
2. class or interface statement.
3. Class (static) variables in the order public, protected,
package (no access modifier), private.4. Instance variables in the order public, protected,
package (no access modifier), private.
5. Constructors.
6. Methods (no specific order).
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
36/60
Methods
Fall 2011cs42036
Method modifiers should be given in the followingorder: static abstract synchronized final nativeThe modifier (if present) must be the firstmodifier public static double square(double a);
// NOT: static public double square(double a);
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
37/60
Types
Fall 2011cs42037
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]
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
38/60
Variables
Fall 2011cs42038
Variables should be initialized where they aredeclared
and they should be declared in the smallest scopepossible
Variables must never have dual meaning Class variables should never be declared public
Variables should be kept alive for as short a time aspossible
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
39/60
Loops
Fall 2011cs42039
Only loop control statements must be included in thefor() construction sum = 0;
for (i = 0; i < 100; i++)
sum += value[i];
// NOT: for (i = 0, sum = 0; i < 100; i++)
// sum += value[i];
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
40/60
Loops
Fall 2011cs42040
Loop variables should be initialized immediatelybefore the loop isDone = false; // NOT: bool isDone = false; while
(!isDone) { // : :
// while (!isDone) {
} // :
// }
The use of do-whileloops can be avoided
The use of breakand continuein loops should be
avoided
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
41/60
Conditionals
Fall 2011cs42041
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) { : }
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
42/60
Conditionals
Fall 2011cs42042
The nominal case should be put in the if-part and theexception 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) // NOT: if (isDone) doCleanup();
doCleanup();
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
43/60
Conditionals
Fall 2011cs42043
Executable statements in conditionals must beavoided InputStream stream = File.open(fileName, "w");
if (stream != null) {
:
}
// NOT:
if (File.open(fileName, "w") != null)) { : }
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
44/60
Miscellaneous
Fall 2011cs42044
The use of magic numbers in the code should beavoided. Numbers other than 0and 1 can beconsidered declared as named constants instead private static final int TEAM_SIZE = 11;
:
Player[] players = new Player[TEAM_SIZE];
// NOT: Player[] players = new Player[11];
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
45/60
Miscellaneous
Fall 2011cs42045
Floating point constants should always be writtenwith 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;
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
46/60
Miscellaneous
Fall 2011cs42046
Floating point constants should always be writtenwith a digit before the decimal point. double total = 0.5; // NOT: double total = .5;
Static variables or methods must always be referedto through the class name and never through aninstance variable. Thread.sleep(1000); // NOT: thread.sleep(1000);
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
47/60
Layout and Comments
Fall 2011cs42047
Basic indentation should be 2. for (i = 0; i < nElements; i++)
a[i] = 0; while (!done) {
doSomething();
done = moreToDo();
}
while (!done)
{
doSomething();
done = moreToDo();
}
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
48/60
Layout and Comments
Fall 2011cs42048
The classand interfacedeclarations should have thefollowing form class Rectangle extends Shape
implements Cloneable, Serializable
{
...
}
Method definitions should have the following form public void someMethod() throws SomeException
{
...
}
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
49/60
Layout and Comments
Fall 2011cs42049
The if-elseclass of statements should have thefollowing form if (condition) {
statements;}else {statements;
}
An empty forstatement should have the followingform for (initialization; condition; update) {
statements;}
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
50/60
Layout & Comments
Fall 2011cs42050
while
do while
switch
try catch
single if else
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
51/60
White Spaces
Fall 2011cs42051
Operators should be surrounded by a space character.
Java reserved words should be followed by a whitespace.
Commas should be followed by a white space.
Colons should be surrounded by white space.
Semicolons in for statements should be followed by aspace character.
Method names can be followed by a white space when itis followed by another name // Create a new identity matrix
Matrix4x4 matrix = new Matrix4x4();
// Precompute angles for efficiencydouble cosAngle = Math.cos(angle);double sinAngle = Math.sin(angle);
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
52/60
White Spaces
Fall 2011cs42052
Variables in declarations can be left aligned TextFile file;
int nPoints;
double x, y;
Statements should be aligned wherever this
enhances readability if (a == lowValue) compueSomething();else if (a == mediumValue) computeSomethingElse();
else if (a == highValue) computeSomethingElseYet();
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
53/60
Comments
Fall 2011cs42053
Tricky code should not be commented but rewritten
All comments should be written in English
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
54/60
Comments
Fall 2011cs42054
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
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
55/60
Comments
Fall 2011cs42055
Javadoc of class members can be specified on asingle 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
*/ */
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
56/60
Comments
Fall 2011cs42056
Use//for all non-JavaDoc comments, includingmulti-line comments. // Comment spanning
// more than one line
Comments should be indented relative to their
position in the code while (true) { // NOT: while (true) {
// Do something // Do something
something(); something();
} }
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
57/60
Comments
Fall 2011cs42057
All public classes and public and protected functionswithin public classes should be documented usingthe Java documentation (javadoc) conventions.
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
58/60
Summary
Fall 2011cs42058
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
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
59/60
Assignment 01
Fall 2011cs42059
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 ofthese
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
Test Case
Successfully unzip the file on user side.
Read Creational Patterns Factory Pattern, Abstract Factory Pattern
Singlton Pattern
8/3/2019 Lecture01-Introduction and How to Write a Maintainable Code
60/60
Questions?
Thats all for today!