Review eleven Common Errors in Java code

Source: Internet
Author: User
Review the eleven Common Errors of Java code-Linux general technology-Linux programming and kernel information. The following is a detailed description. Code reviews are one of the most important ways to eliminate bugs, which are especially effective in most cases. Because the code review itself targets objects, it is to overlook the problems and bugs of the entire code in the test process. In addition, code review is of great benefit to eliminate specific errors, especially those that can be easily found when reading the code, which are often not easily identified by tests on the machine. This article provides some constructive suggestions on common issues in Java code so that you can notice these common detailed errors during code review.

It is usually easier to pick a wrong job for others than to find your own mistakes. The existence of different perspectives also explains why the author needs to edit and why athletes need coaches. Not only should we not reject criticism from others, but we should welcome others to discover and point out the shortcomings in our programming work. We will benefit a lot.

Code inspection is one of the most powerful technologies to improve code quality, code Review-errors found by colleagues looking for errors in the code-are different from those found in the test, so the relationship between the two is complementary, rather than competitive.

If the examiner can consciously find specific errors, rather than simply browsing the code without any purpose, the code review effect will get twice the result with half the effort. In this article, I listed 11 Common Errors in Java programming. You can add these errors to the checklist of your code review, so that after the code review, you can be sure that there are no such errors in your code.

I. common error 1 #: copying strings multiple times

One error that cannot be found during the test is to generate multiple copies of an immutable object. Immutable objects cannot be changed, so you do not need to copy them. The most common immutable object is String.

If you must change the content of a String object, you should use StringBuffer. The following code works properly:

String s = new String ("Text here ");

However, this code has poor performance and does not need to be so complicated. You can also rewrite the above Code in the following ways:

String temp = "Text here ";
String s = new String (temp );

However, this code contains extra strings, which is not completely necessary. Better code:

String s = "Text here ";

2. Common Error 2 #: no object returned by clone

Encapsulation is an important concept of object-oriented programming. Unfortunately, Java provides convenience for accidentally breaking the encapsulation-Java allows the return of reference for private data ). The following code reveals this point:

Import java. awt. Dimension;
/*** Example class. The x and y values shoshould never * be negative .*/
Public class Example {
Private Dimension d = new Dimension (0, 0 );
Public Example (){}

/*** Set height and width. Both height and width must be nonnegative * or an exception is thrown .*/
Public synchronized void setValues (int height, int width) throws IllegalArgumentException {
If (height <0 | width <0)
Throw new IllegalArgumentException ();
D. height = height;
D. width = width;
}

Public synchronized Dimension getValues (){
// Ooops! Breaks encapsulation
Return d;
}
}

The Example class ensures that the height and width values stored by the class are never negative. An exception is triggered when you try to use the setValues () method to set a negative value. Unfortunately, because getValues () returns a reference to d instead of a copy of d, you can write the following Destructive code:

Example ex = new Example ();
Dimension d = ex. getValues ();
D. height =-5;
D. width =-10;

Now, the Example object has a negative value! If the getValues () caller never sets the width and height values of the returned Dimension object, such errors cannot be detected by testing alone.

Unfortunately, with the passage of time, the client code may change the value of the returned Dimension object. At this time, it is boring and time-consuming to find the root cause of the error, especially in multi-threaded environments.

A better way is to get getValues () to return a copy:

Public synchronized Dimension getValues (){
Return new Dimension (d. x, d. y );
}

Now, the internal status of the Example object is secure. The caller can change the copy status as needed. To modify the internal status of the Example object, you must use setValues.

Iii. Common Errors 3 # unnecessary cloning

We now know that the get method should return a copy of the internal data object instead of a reference. However, things are not absolute:

/*** Example class. The value shoshould never * be negative .*/
Public class Example {
Private Integer I = new Integer (0 );
Public Example (){}

/*** Set x. x must be nonnegative * or an exception will be thrown */
Public synchronized void setValues (int x) throws IllegalArgumentException {
If (x <0)
Throw new IllegalArgumentException ();
I = new Integer (x );
}

Public synchronized Integer getValue (){
// We can't clone Integers so we makea copy this way.
Return new Integer (I. intValue ());
}
}

This code is safe, but as in error 1 #, it does extra work. An Integer object, like a String object, is immutable once created. Therefore, it is safe to return an internal Integer object instead of copying it.

The getValue () method should be written as follows:

Public synchronized Integer getValue (){
// 'I' is immutable, so it is safe to return it instead of a copy.
Return I;
}

Java programs include more immutable objects than C ++ programs. Several unchangeable classes provided by JDK include:

· Boolean
· Byte
· Character
· Class
· Double
· Float
· Integer
· Long
· Short
· String
· Subclass of most exceptions
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.