Throw out those 4 Bad Practices in Java
Well if you are writing Java code from quite a some time you must have came across quite a number of bad practices ,I am going to show 4 bad practices which are very common and we should definitely try to avoid them, I am listing 4 of so many bad practices out there.
Bad Practice 1 – “Comparison of String parameter using ==”
How often you have seen this in your code ! Answer to this is well almost every now and then. Let see it by an example:
public class BadPractice { public static void main(String args[]) { String firstName=new String("XYZ"); String secondName=new String("XYZ"); System.out.println(firstName==secondName); } }
Well what would be the output of the program,if you are thinking that output of the program would be “true” then you need to think again because the output be “false”.
What was expected is that it should compare the equality , but here it is comparing the references !.
So this should totally be avoided. This is a bad practice can lead to erroneous results at runtime. So .equals method should be used here in order to avoid any erroneous results at the runtime.
Note: However if you look at the following program it would return you “true”.
public class BadPractice { public static void main(String args[]) { String firstName="XYZ"; String secondName="XYZ"; System.out.println(firstName==secondName); } }
Well reason for this program giving “true” as the output is that because when you say String firstName=”XZY”, so it make a constant pool and keep the string out there , so any new object created in this way String newString=”XYZ” it is going to pick it up from the same pool and then when you do comparison you are actually comparing the references which are sure shortly equal. It is because of this practice usually we goes for “==” rather then “.equals” method.
Bad Practice 2 – Method Igonring Exception
Well this is one more common mistake which many of the programmers do it , some does it deliberately, and some do it without knowing what actually they are doing. Let see it in the below example:
public class BadPractice { public void doSomething() { try { //Some code here }catch (Exception e){ //Bad practice , either //re throw the exception of take some actions. } } }
If you see the above code the exception will be ignored, in general, exceptions should be handled or reported in some way, or they should be thrown out of the method.
Bad Practice 3 – “Exception Created but never thrown”
Well this one is again common mistake which is mostly done my newbie programmers, let us see the code in the following example:
public void doSomething() { int x=-1; if (x < 0) new IllegalArgumentException("x must be nonnegative"); }
The intent here was to thrown a new IllegalArgumentException when the value of x is negative but what has happened is the the exception is created but it is not thrown.
Correct way of doing the same thing is shown below, you should throw the exception explicitly , because that is what you are expecting.
public void doSomething() { int x=-1; if (x < 0) throw new IllegalArgumentException("x must be nonnegative"); }
Bad Practice 4 – “Concatenating strings using + in a loop”
Well this is one of the common mistake done by almost 99% of the programmer and is identfied very late during the project development. But it is better late than never so let see this by an example:
public class BadPractice { public void doSomething() { String fields[]={"1","2","3","4"}; //Bad Way of doing it String str = ""; for (int i = 0; i < fields.length; ++i) { str = str + fields[i]; } } }
The method seems to be building a String using concatenation in a loop. In each iteration, the String is converted to a StringBuffer/StringBuilder, appended to, and converted back to a String. Each time a new object of string is constructed which can lead to huge number of objects in the memory to be created.
So better way of doing the same thing is shown below.
public class GoodPractice { public void doSomething() { String fields[]={"1","2","3","4"}; // Good Way of doing it StringBuffer buf = new StringBuffer(); for (int i = 0; i < fields.length; ++i) { buf.append(fields[i]); } String s = buf.toString(); } }
So as you can see in the above code only one object is created irrespective of the fields array length.And in the end it is taken into the string object.
I hope you enjoyed reading the bad practices, your suggestions and feedback are most welcome.
You might also be interested in reading How to Find out Bad Practices and Bugs Using Find Bugs
Related posts:







Use a StringBuilder unless you need Thread safety.
Nice one.Do let me know such links avialable for such related topics on coding in java
Cool, the third bad practice i have seen at various places.
compiler changes string catenation automatically to StringBuffer…
Did you actually find a lot of occurrences of these in the field? They’re typical rookie or student mistakes – but no professional of any merit would look at any of these bad practices and think “Gee, the tutorials should mention these!” — because the tutorials DO mention them.
I have seen experience people doing such kind of mistakes.
Especially #4
Here’s one of the worst practices in Java:
Students of my Branch in college have started confusing notepad as Java because they code the program in notepad……
Some even open up notepad when called upon to open Java…..
There’s nothing wrong with coding in Notepad.
On Point 4: It was noted that we use StringBuffer in place of String Concatenation. I believe a good option will be using StringBuilder in place of StringBuffer.
I have never come across a valid case till date which demonstrates StringBuffer advantages of being thread safe over StringBuilder. Even though StringBuffer is internally synchronized, if the order in which it has to be written / modified / mutated then we will need some form of synchronization.If this is the case then why not prefer StringBuilder with synchronization which has performance benefits.
BTW most of times we string manipulation is often handled by a single thread.
Predictions are StringBuffer will be obsolete in future.