Thursday, October 22, 2009

Best Practices in programming

I though to write a continuous article describing best practices in programming. Here I’m not going to talking about  coding conventions but talking about enhanced cording techniques you can use.

Using IO, Network connections

InputStream streamRead =null;
try {
    //  Use InputStream to do your work   
} catch (Exception ex) {
    // Exception Handling
}
finally
{
    try {
    // Try to close the stream, This may also give erros
    // resulting opened stream
    streamRead.close();
    } catch (IOException e) {
    }
    // Set Stream to null to prevent
    // unwanted openings
    streamRead=null;
}

Not to use methods in loop’s conditions

// This is not optimized
for (int i = 0; i < elements.capacity(); ++i)
{
    // Code Here     
}
 
// This is optimized,
// elements.capacity() only call in one time
int capacity = elements.capacity();
for (int i = 0; i < capacity; ++i)
{
    // Code Here  
}

Use String Buffer wherever possible.

// This will create two string and
// append it
String str = new String ("My Name is : ");
str += "Mleick";
 
// This is better
StringBuffer str = new StringBuffer ("My Name is :");
str.append("Mleick!!");

Use Threads to call server calls where ever possible.


This prevents user to feel as hang the system during the network calls. I’ll write a article including asynchronous server calls.   

Post a Comment