Lecture01-Introduction and How To Write A Maintainable Code
Lecture01-Introduction and How To Write A Maintainable Code
Lecture-00-Course Outline
Aatif Kamal, Dept. of Computing [email protected]
Agenda
cs420
Fall 2011
Reading material
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
Course details
Will be available online Usually one (1) hour after the lecture
Office hours:
cs420
Fall 2011
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
Writing maintainable/extensible code Methods of debugging, logging, profiling Design patterns J2EE Enterprise Application Development
Java Technologies
Outcomes
cs420
Fall 2011
Course outline
1.
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.
Lets begin!
Ref: csc.liv.ac.uk
A programmer should be able to understand it when reading it for the first time
It should work!
10
cs420
Fall 2011
Laziness Use all the tools in the box Inexperience ~ havent extended a program Indifference ~ Elitism
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
14
cs420
Fall 2011
Code formatting
Always use spaces Set your IDE to replace TABS with spaces
15
cs420
Fall 2011
Remember!!!
Any violation of the convention is allowed if it enhances readability
Naming
mypackage, com.company.application.ui
Names representing types must be nouns and written in mixed case starting with upper case
Line, AudioSystem
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:
19
cs420
Fall 2011
Naming
Names representing methods must be verbs and written in mixed case starting with lower case
getName(), computeTotalWidth()
20
Naming
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
Naming
The name of the object is implicit, and should be avoided in a method name
23
cs420
Fall 2011
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
int[] values;
cs420 Fall 2011
25
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 )
26
cs420
Fall 2011
Variables named j, k etc. should be used for nested loops only. Abbreviations in names should be avoided
27
cs420
Fall 2011
final int COLOR_RED = 1; final int COLOR_GREEN = 2; interface Color { final int RED = 1; final int GREEN = 2; final int BLUE = 3; }
28
cs420
Fall 2011
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
Classes that creates instances on behalf of others (factories) can do so through method new[ClassName]
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
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
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
34
cs420
Fall 2011
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.
37
cs420
Fall 2011
Variables
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
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
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
if (isDone) doCleanup();
42
cs420
Fall 2011
Conditionals
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.
Static variables or methods must always be refered to through the class name and never through an instance variable.
46
cs420
Fall 2011
for (i = 0; i < nElements; i++) a[i] = 0; while (!done) { doSomething(); done = moreToDo(); } while (!done) { doSomething(); done = moreToDo(); }
47
cs420
Fall 2011
The class and interface declarations should have the following form
48
cs420
Fall 2011
49
cs420
Fall 2011
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
file; nPoints; x, y;
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
/** * 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
// 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
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
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
59
Questions?
Thats all for today!