Some common problem summaries in Java programming _java

Source: Internet
Author: User
Tags int size numeric value

This article lists some of the more typical errors I've seen in the Java code of my colleagues around me. Obviously, static code analysis (our team is using Qulice) is not likely to uncover all the problems, which is why I want to list them here.

If you feel that something is missing, please do not hesitate to enlighten me, I will be happy to add them.

All of the errors listed below are largely related to object-oriented programming, especially Java OOP.

Class name

Read this short essay "What Is an object". Class should be an abstract entity in real life, not "validators", "Controller", "managers" these things. If your class name ends with "ER"-then it's a bad design.

Of course, the tool class is also an inverse mode, such as Apache StringUtils, FileUtils, and Ioutils. These are the representatives of poor design. Extended reading: An alternative to tool classes in OOP.

Of course, do not use prefixes or suffixes to differentiate between classes and interfaces. For example, these names are wrong: Irecord, Ifaceemployee, or Recordinterface. Generally speaking, the interface name should be the name of the real-life entity, and the class name should be able to explain its implementation details. If this implementation is not particularly descriptive, it can be called default, simple, or something like that. For example:

Copy Code code as follows:

Class Simpleuser implements User {};
Class Defaultrecord implements record {};
Class suffixed implements Name {};
Class validated implements Content {};

Method name

Method can return a value, or it can return void. If the method returns a value, its name should indicate what it returns, for example (never use a Get prefix):

Copy Code code as follows:

Boolean isValid (String name);
String content ();
int ageof (file file);

If it returns void, then its name should indicate what it did. Like what:

Copy Code code as follows:

void Save (file file);
void process (Work Work);
void append (file file, String line);

There is only one exception to the rules mentioned earlier.--junit's test method does not count. Here's what we're going to talk about.

The name of the test method

In junit test cases, the method name should be an English statement with no spaces. One example would make it clearer:

Copy Code code as follows:

/**
* HttpRequest can return it content in Unicode.
* @throws Exception If test fails
*/
public void Returnsitscontentinunicode () throws Exception {
}

Your first words in Javadoc should begin with the name of the class you want to test, and then a can. Therefore, your first sentence should be similar to "Somebody can do something".

The method name is the same, but there is no theme. If I add a topic to the middle of the method name, I can get a complete sentence, as in the example above: "HttpRequest returns its content in Unicode".

Please note that the name of the test method does not begin with can. Only the annotations in Javadoc will begin with can. In addition, the method name should not begin with a verb.

In practice, it is best to declare a test method as throwing exception.

Variable name

Avoid the combination of variable names, such as TimeOfDay, FirstItem, or HttpRequest. This is true for both class variables and the variables within the method. The variable name should be long enough to avoid ambiguity within its visible scope, but not too long if you can. The name should be a noun in the singular or plural form, or an appropriate abbreviation. Like what:

Copy Code code as follows:

List<string> names;
void Sendthroughproxy (file file, Protocol proto);
Private File content;
public HttpRequest request;

Sometimes, if the constructor is to save the argument to a newly initialized object, its arguments and the name of the class attribute may conflict. In this case, I suggest that you remove the vowels and use abbreviations.

Example:

Copy Code code as follows:

public class Message {
Private String recipient;
Public message (String RCPT) {
This.recipient = RCPT;
}
}

A lot of times, take a look at the variable's class name to know what the variable should be named. Just use its lowercase form, like this is very reliable:

Copy Code code as follows:

File file;
User user;
Branch Branch;

However, the underlying type should never do so, such as integer number or string string.

If there are many variables of different nature, you can consider the use of adjectives. Like what:

Copy Code code as follows:

String Contacts (string left, string right);

Construction method

Regardless of the exception, there should be only one constructor used to store the data in an object variable. Other construction methods use different parameters to invoke the constructor method. For example:

Copy Code code as follows:

public class Server {
Private String address;
Public Server (String URI) {
this.address = URI;
}
Public Server (Uri Uri) {
This (uri.tostring ());
}
}

One-time variable

In any case, you should avoid using one-time variables. What I mean by "one-off" here is a variable that is used only once. Like the following:

Copy Code code as follows:

String name = "Data.txt";
return new File (name);

The above variables will only be used once, so this code can be made to form this way:
Copy Code code as follows:

return new File ("Data.txt");

Sometimes, in rare cases--mainly for better formatting--a one-time variable may be used. However, such a situation should be avoided as far as possible.

Abnormal

Needless to be saying, never swallow an exception yourself, but should when it is passed as far as possible. Private methods should always throw the checked exception out.

Do not use exceptions for process control. Let's say the following code is wrong:

Copy Code code as follows:

int size;
try {
Size = This.filesize ();
catch (IOException ex) {
size = 0;
}

What if IOException prompts "disk is full"? Would you also think that the file size is 0, and then proceed down?

Indent

With regard to indentation, the main rule is that the opening parenthesis is either at the end of the line, or it is closed on the same line (the opposite of the closing parenthesis). For example, the following is not true because the first opening parenthesis is not closed on the same line, and there are other characters behind it. The second parenthesis also has a problem because it has a character in front of it, but the corresponding opening parenthesis is not on the same line:

Copy Code code as follows:

Final file File = new file (directory,
"File.txt");

The correct indentation should be this:
Copy Code code as follows:

Stringutils.join (
Arrays.aslist (
"A",
"Second Line",
Stringutils.join (
Arrays.aslist ("A", "B")
)
),
"Separator"
);

The second important rule about indentation is that you should write as many as you want in one line-the upper limit is 80 characters. The above example does not satisfy this, it can also shrink:
Copy Code code as follows:

Stringutils.join (
Arrays.aslist (
"The", "second line",
Stringutils.join (Arrays.aslist ("A", "B"))
),
"Separator"
);

Excess constants

When you want to share information in the methods of a class, you should use class constants, which should be specific to your class. Don't use constants as substitutes for strings or literal values--this is a very bad practice, and it can pollute your code. A constant, like any object in OOP, should have its own meaning in the real world. Look at what these constants mean in real life:

Copy Code code as follows:

Class Document {
private static final String D_letter = "D"; Bad Practice
private static final String EXTENSION = ". Doc"; Good practice
}

Another common mistake is to use constants in a unit test to avoid the occurrence of redundant strings or literal values in a test method. Don't do this! Each test method should have its own input value.

Use the new text or numeric value in each new test method. They are independent of each other. So why do they share the same input constants?

Test data coupling

The following is an example of data coupling in test methods:

Copy Code code as follows:

User user = New User ("Jeff");
Maybe some other code here
Matcherassert.assertthat (User.Name (), Matchers.equalto ("Jeff"));

In the last line, "Jeff" and the same string literal in the first row are coupled. If, after a few months, someone wants to change the value of the third line, it will take time to find out where the "Jeff" is used in the same method.

To avoid this, you'd better introduce a variable.

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.