Java Coding Practices
Download
Report
Transcript Java Coding Practices
Java Coding Practices
R.SANTHANA GOPALAN
Java Coding Practices
Avoid call method inside the “for” loop
Wrong
for( int i =0; i < vec.size(); i++)
{
...
}
Unnecessary vec.size() will be called every time the loop
continues. We can store the vec.size() in a “int” datatype and we
can use in a “for” loop.
Correct
int vec_size=vec.size();
for(int i =0; i < vec_size; i++)
{
...
}
Wrong Example:
boolean b = threadObj.isAlive();
for( ; b; )
{
….
}
Java Coding Practices
Avoid Recursive Method
If possible try to avoid Recursive method
calling.
If you don’t know the limit then the
StackOverFlow error will happen.
Java Coding Practices
isVisible() -or- getVisible()
If the method returns the boolean value then
the method name should be starts with “is”.
If the method returns non-boolean value
then the method name should be starts with
“get”. Eg. getBackground().
Java Coding Practices
Converter Method
Initial lowercase word is "to", remaining
subwords are capitalized.
Example:
toGenie(), toTiger(),
Java Coding Practices
Getters Method
methods that query state.
Initial lowercase word is "get", remaining
sub words are capitalized and, if possible,
are exactly the same as the name of the
instance field to which they relate.
Example:
getDjinnName(), getCatColor()
Java Coding Practices
Setters Method
methods that set state
Initial lowercase word is "set", remaining
sub-words are capitalized and, if possible,
are exactly the same as the name of the
instance field to which they relate.
Example:
setDjinnLocation()
Java Coding Practices
Method – pass by reference (or) value?
Be very careful by passing the Objects to
the another method.
If the method changes the value in the
method then make sure that is documented.
Java Coding Practices
Do you know the answer?
public void tricky(Point arg1, Point arg2)
{
arg1.x = 100;
arg1.y = 100;
Point temp = arg1;
arg1 = arg2;
arg2 = temp;
}
public static void main(String [] args)
{
Point pnt1 = new Point(0,0);
Point pnt2 = new Point(0,0);
System.out.println("X: " + pnt1.x + " Y: " +pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
System.out.println(" ");
tricky(pnt1,pnt2);
System.out.println("X: " + pnt1.x + " Y:" + pnt1.y);
System.out.println("X: " + pnt2.x + " Y: " +pnt2.y);
}
Java Coding Practices
Answer:
X: 0 Y: 0
X: 0 Y: 0
X: 100 Y: 100
X: 0 Y: 0
Avoid this kind of programming.
Java Coding Practices
If you override Object.equals(), also
override Object.hashCode(), and viceversa.
Reason:
Essentially all containers and other utilities
that group or compare objects in ways
depending on equality rely on hashcodes to
indicate possible equality.
Java Coding Practices
Import classes one by one instead of
importing a whole package, thus it
becomes clearer.
Example:
import com.adventnet.beans.graph.LineGraph;
import com.adventnet.beans.graph.BarGraph;
Java Coding Practices
Don’t declare variables as package
level access. The default access level is
package.
Wrong
int status;
Correct
private int status;
Java Coding Practices
if”
(or) “else if” - Document it perfect.
Example:
if(prop.containsKey("caseid"))
{
//Do some action
}
if(prop.containsKey("casemessage"))
{
//Do some action
}
Java Coding Practices
Keep
the block level less than 4.
Wrong Example:
if (condition1)
{
if(condition2)
{
if(condition3)
{
if(condition 4)
{
if (condition5)
{
Java Coding Practices
Don’t call the method unnecessarily
Wrong Example:
if(ae.getA().equals("Default"))
{
}
else if(ae.getA().equals(“One”))
{
}
Java Coding Practices
Correct
String aVal=ae.getA();
if(aVal.equals("Default"))
{
}
else if(aVal.equals(“One”))
{
}
Java Coding Practices
Don’t use “\n” for the new line character
Wrong Example:
textarea.append(message + “\n”);
Correct Example:
Declare private static String lineseparator =
System.getProperty(“lineseparator”);
textarea.append(message + lineseparator);
Java Coding Practices
Use File.separator for the file separator.
If it is really required then use “/”.
Wrong
fname=“help/index.html”
Correct
fname=“help” +File.separator + “index.html”
Java Coding Practices
Be careful while add the debug
statements in
StringTokenizer.nextToken()
Wrong Example
StringTokenizer st = new StringTokenizer(strValue)
while(st.hasMoreElements())
{
String s = st.nextToken();
System.out.println(st.nextToken());
----}
Java Coding Practices
StringBuffer - Performance
If you know the size then instantiate
StringBuffer(int n). This will give high
performance.
Java Coding Practices
FileOutput Stream is costly.
Wrong
fos = new FileOutputStream(f);
fos.write(htmltagstart.getBytes());
fos.write(headtagstart.getBytes());
fos.write(metatag.getBytes());
Java Coding Practices
Correct
StringBuffer sb = new StringBuffer(1000);
sb.append(htmltagstart);
sb.append(headtagstart);
sb.append(metatag);
fos = new FileOutputStream(f);
fos.write(sb.toString().getBytes());
Java Coding Practices
Do proper close operation. Otherwise it
will create lot of problem in the runtime.
Example:
FileOutStream.close()
ResultSet.close()
Java Coding Practices - Question
FileInputStream: read() Vs. read(byte[]) .
Which will give more performance?
FileOutputSteam: write() Vs.
write(byte[]). Which will give more
performance?
Java Coding Practices
Serializable
Serialization can be very costly.
Using the transient keyword reduces the
amount of data serialized.
Wrong Example:
private JFrame;
Correct Example:
private transient JFrame;
Java Coding Practices
Explicitly set the layout of the
panel/Frame/Dialog. Don’t leave it to
default.
Panel.setLayout(new BorderLayout());
Java Coding Practices
Use the Constant to add the component
in BorderLayout.
Wrong Example:
panel.add(“Center”,textarea);
Correct Example:
panel.add(textarea,BorderLayout.CENT
ER);
Java Coding Practices
Don’t call UIManager.setLookAndFeel()
in your program. Only the main class can
call this method.
UIManager.getCrossPlatformLookAndFeelC
lassName());
Java Coding Practices - Question
What is wrong?
private int sum;
public CalculateSum(int sum)
{
sum=sum;
}
Java Coding Practices
JOptionPane(Object,…) - What is the
difference between passing “null” value
and passing the exact JFrame object?
Java Coding Practices
Don’t write anonymous classes
Wrong:
textarea.addActionListener(new ActionListener(){
…….
…….
};
Java Coding Practices
Don’t use “goto” command and “labelled”
statements.
Java Coding Practices
Use Bean Builder to develop UI.
….features
Java Coding Practices
Common Mistake
Comparing String using “==“ operator.