Skip navigation
2012
navurinv

Temporary Fields

Posted by navurinv Jan 30, 2012

If a variable need not be shared across methods, make it local.

private int x;

int method() {

x = 0;    // if you forget to initialize, you're dead

...         // do some stuff

return x;

}

 

int method() {

int x = 0;

...         // do some stuff

return x;

}

navurinv

Using Magic Numbers

Posted by navurinv Jan 27, 2012

Magic numbers are not readable

for (int i = 1; i =< 52; i++) {

j  =  i + randomInt(53 - i) – 1

swapEntries(i, j)

}

Replace with constants.

final int DECKSIZE = 52;

for (int i = 1; i =< DECKSIZE; i++) {

j  =  i + randomInt(DECKSIZE + 1 - i) – 1

swapEntries(i, j)

}

navurinv

Empty Catch Block

Posted by navurinv Jan 24, 2012

No indication that an exception has occurred!

Implementation inheritance is difficult to debug.

Ask yourself: “Is this a kind of…?”

Alternatives:

Prefer interface inheritance.

Prefer composition over inheritance.

navurinv

Returning null

Posted by navurinv Jan 24, 2012

Causes NullPointerExceptions.

Instead, return…

empty objects

custom-made “Null Objects”

Binary numbers cannot exactly represent decimals.

Use BigDecimal for currency calculations.

...using the constructor that takes a String as a parameter.

Don’t:

            String str = new String(“This is bad.”);

 

Do:

            String str = “This is good.”;

navurinv

Temporary Fields

Posted by navurinv Jan 23, 2012

If a variable need not be shared across methods, make it local.

private int x;

int method() {

x = 0;    // if you forget to initialize, you're dead

...         // do some stuff

return x;

}

 

int method() {

int x = 0;

...         // do some stuff

return x;

}

navurinv

Accessible Fields

Posted by navurinv Jan 23, 2012

Fields should always be private except for constants.

Accessible fields cause tight coupling.

Accessible fields are corruptible.

If a field needs to be accessed, use “get” and “set” convention.

navurinv

Duplicate Code!

Posted by navurinv Jan 23, 2012

Every time you need to make a change in the routine, you need to edit it in several places. 

Don’t copy-paste code!

navurinv

Null pointers

Posted by navurinv Jan 23, 2012

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.

navurinv

Capitalization errors

Posted by navurinv Jan 23, 2012

While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-

all methods and member variables in the Java API begin with lowercase letters

all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()

 

While there's no silver bullet for detecting this error, you can easily train yourself to make less of them. There's a very simple trick you can learn :-

all methods and member variables in the Java API begin with lowercase letters

all methods and member variables use capitalization where a new word begins e.g - getDoubleValue()

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 amount)

    {

        count = amount;

    }

   

    public synchronized int getCount()

    {

        return count;

    }

}

If you've come from a C/C++ background, you may not find this quite as much a problem as those who have used other languages. In Java, arrays are zero-indexed, meaning that the first element's index is actually 0

public static void main(String args[])

    {

    try {

    // Your code goes here..

    }

    catch (Exception e)

    {

    System.out.println ("Err - " + e );

    }

    }

When you pass a primitive data type, such as a char, int, float, or double, to a function then you are passing by value. That means that a copy of the data type is duplicated, and passed to the function. That means that a copy of the data type is duplicated, and passed to the function. If the function chooses to modify that value, it will be modifying the copy only.

 

When you pass a Java object, such as an array, a vector, or a string, to a function then you are passing by reference.So that means that if you pass an object to a function, you are passing a reference to it, not a duplicate. Any changes you make to the object's member variables will be permanent

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.

Ex. String Comparison

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

// Bad way if ( (abc + def) == "abcdef" ) { ….. }

 

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

Fortunately, even if you don't spot this one by looking at code on the screen, your compiler will. Most commonly, it will report an error message like this : "Can't convert xxx to boolean", where xxx is a Java type that you're assigning instead of comparing.

Accessing non-static member variables from static methods (such as main)

 

 

public class StaticDemo

      {

        public String my_member_variable = "somedata";

        public static void main (String args[])

        {

        // Access a non-static member from static method

                System.out.println ("This generates a compiler error" +

            my_member_variable );

        }

     }

 

 

 

Mistyping the name of a method when overriding

 

 

If you mistype the name, you're no longer overriding a method - you're creating an entirely new method, but with the same parameter and return type.


 

Solution: Using LIKE clause in SQL statement like below is simple:

pstmt = conn.prepareStatement("SELECT * FROM table_name WHERE field_name LIKE ?");

String var = "some_string";
pstmt.setString(1, var);


This works fine.

Now, to modify this query in order to search between strings is little tricky. Below is the SQL statement to counter it:


pstmt = conn.prepareStatement("SELECT * FROM table_name WHERE field_name LIKE '%' || ? || '%'");

String var = "substring";
pstmt.setString(1, var);



Use the '||' concatenation operator to combine % and the ?. This should resolve any issues while trying to perform LIKE searches with-in strings. Doing LIKE searches with % infront and back may cause some performance degradation, so you need to look at the explain plan of your query how it impacts performance. Moral of the story use % in front and back only when absolutely required.

Filter Blog