Wednesday, January 5, 2011

Java : Error Patterns in Programming - The Top errors List-1

1. Accessing non-static member variables from static methods (such as main)
This is a quite often committed mistake especially who are newly introduced to java.Your first few days with java can be a real mess with this error.
Take for example the following application, which will generate a compiler error message.

public class StaticDemo
{
        public String str1 = "teststr";
        public static void main (String args[])
        {
// Access a non-static member from static method
                System.out.println ("This generates a compiler error" + str1 );
        }
}
If you want to access its member variables from a non-static method (like main), you must create an instance of the object.
Here's a simple example of how to correctly write code to access non-static member variables, by first creating an instance of the object.

public class Non-StaticDemo
{
        public String str1 = "tststr";


        public static void main (String args[])
        {
                NonStaticDemo nsd = new NonStaticDemo();


// Access member variable of demo
                System.out.println ("No error here" + nsd.my_member_variable );
        }
}

---------------------Please click on "more" below for the enitre list -------------------------




2. Index Of

Most software bugs are caused by assumptions made by the programmer.
One common assumption developers make is that file names have only one period to separate the file name from the file extension.
It is common to see code that finds the first period and everything after that period is assumed to be the extension.
Other assumptions regarding file names include that extensions are three characters long or that the file name does not have special characters.
The following code snippet is a dramatization of code I have seen in the field, which incorrectly tries parse the file extension.

String filename = "a.file.path.ext";
int index = filename.indexOf(".");
String extension = filename.substring(index);

A different approach, which would have the desired result is to use the lastIndexOf() instead.

3. The famous ( "the infamous" to call it better) - Null Pointer Exceptions



Null pointers are one of the most common errors that Java programmers make.
Compilers can't check this one for you - it will only surface at runtime, and if you don't discover it, your users certainly will.

When an attempt to access an object is made, and the reference to that object is null, a NullPointerException will be thrown.
The cause of null pointers can be varied, but generally it means that either you haven't initialized an object, or you haven't checked the return value of a function.

Many functions return null to indicate an error condition - but unless you check your return values, you'll never know what's happening.
Since the cause is an error condition, normal testing may not pick it up - which means that your users will end up discovering the problem for you.
If the API function indicates that null may be returned, be sure to check this before using the object reference!

Another cause is where your initialization has been sloppy, or where it is conditional.
For example, examine the following code, and see if you can spot the problem.

public static void main(String args[])
{
// Accept up to 3 parameters
String[] list = new String[3];


int index = 0;


while ( (index < args.length) && ( index < 3 ) )
{
list[index++] = args[index];
}


// Check all the parameters
for (int i = 0; i < list.length; i++)
{
if (list[i].equals "-help")
{
// .........
}
else
if (list[i].equals "-cp")
{
// .........
}
// else .....
}
}
This code (while a contrived example), shows a common mistake. Under some circumstances, where the user enters three or more parameters, the code will run fine.
 If no parameters are entered, you'll get a NullPointerException at runtime.
 Sometimes your variables (the array of strings) will be initialized, and other times they won't.

 One easy solution is to check BEFORE you attempt to access a variable in an array that it is not equal to null.

4. Comparing two objects ( == instead of .equals)

When we use the == operator, we are actually comparing two object references, to see if they point to the same object.
We cannot compare, for example, two strings for equality, using the == operator.
We must instead use the .equals method, which is a method inherited by all classes from java.lang.Object.

Here's the correct way to compare two strings.

String abc = "abc"; String def = "def";


// Incorrect way
if ( (abc + def) == "abcdef" )
{
    ......
}
// Good way
if ( (abc + def).equals("abcdef") )
{
   .....


5. Preventing concurrent access to shared variables by threads

When writing multi-threaded applications, many programmers (myself included) often cut corners, and leave their applications and applets vulnerable to thread conflicts.
When two or more threads access the same data concurrently, there exists the possibility (and Murphy's law holding, the probability) that two threads will access or modify the same data at the same time.
Don't be fooled into thinking that such problems won't occur on single-threaded processors.
While accessing some data (performing a read), your thread may be suspended, and another thread scheduled.
It writes its data, which is then overwritten when the first thread makes its changes.

Such problems are not just limited to multi-threaded applications or applets. If you write Java APIs, or JavaBeans, then your code may not be thread-safe.
Even if you never write a single application that uses threads, people that use your code WILL.
For the sanity of others, if not yourself, you should always take precautions to prevent concurrent access to shared data.

How can this problem be solved? The simplest method is to make your variables private (but you do that already,  right?) and to use synchronized accessor methods. Accessor methods allow access to private member variables, but in a controlled manner.
Take the following accessor methods, which provide a safe way to change the value of a counter.

public class MyCounter
{
private int count = 0; // count starts at zero


public synchronized void setCount(int counter)

count = counter;
}

public synchronized int getCount()
{
return count;
}
}

No comments:

Post a Comment

subversion video