Reprint: 10 Practical But paranoid Java programming techniques

Source: Internet
Author: User
Tags case statement

After being immersed in coding for a while (for example, I've been in the program for almost 20 years or so), you'll be getting used to these things all the time. Because, you know ...

Anything can go wrong, yes, it does.

That's why we use defensive programming, which is the reason for some paranoid habits. Here are some of the 10 most useful but paranoid Java programming techniques I personally consider. Let's take a look:

Put string string in front

To prevent accidental nullpointerexception exceptions, we usually put string on the left side of the Equals () function to implement a string comparison, as in the following code:

Bad
if (Variable.equals ("literal")) {...}
Good
if ("literal". Equals (variable)) {...}
This is what you can do with your mind, from the bad version of the code to the good version of the code, which doesn't lose anything. Welcome to different points of view ...

Don't trust the early JDK API

In the early days of Java, programming was a very painful thing. Those APIs are still very immature, and perhaps you've come across the following code block:

string[] files = file.list ();
Watch out
if (Files! = null) {
for (int i = 0; i < files.length; i++) {
...
}
}
Look paranoid? Maybe, but please look at Javadoc:

If this virtual path does not represent a folder directory, this method returns NULL. Otherwise, a string array will be returned, each representing a file or folder in the directory.

Yes, that's right. We can add some checks:

if (File.isdirectory ()) {
string[] files = file.list ();
Watch out
if (Files! = null) {
for (int i = 0; i < files.length; i++) {
...
}
}
}

Don't believe "-1"

I know it's paranoid, but Javadoc the String.IndexOf () method explicitly states that the position index of the specified character appears within the object for the first time, and if 1 indicates that the character is not in the character sequence.

So using-1 is a matter of course, right? I said wrong, please look at the following code:

Bad
if (String.IndexOf (character)! =-1) {...}
Good
if (String.IndexOf (character) >= 0) {...}
Who knows. Maybe they changed the encoding, the string is not case-sensitive, maybe the better way is to return-2? Who knows.

Avoid accidental assignment of values

Yes. This kind of thing may often happen.

Ooops
if (variable = 5) {...}
Better (because causes an error)
if (5 = variable) {...}
Intent (remember. Paranoid JavaScript: = = =)
if (5 = = = variable) {...}
So you can put the comparison constant on the left side so that there is no accidental assignment error.

Check for null and length

Anyway, as long as you have a collection, an array, etc., make sure it exists and is not empty.

Bad
if (Array.Length > 0) {...}
Good
if (array! = NULL && array.length > 0) {...}
You don't know where these arrays come from, perhaps from an earlier version of the JDK API, who knows.

All the methods are final.

You may tell me your principle of open/closed, but it's all nonsense. I don't believe you (inherit all the subclasses of my parent class correctly), and I don't believe myself (accidentally inheriting all the subclasses of my parent class). So the final logo is strictly used for those ways that make sense.

Bad
public void Boom () {...}
Good. Don ' t touch.
Public final void Donttouch () {...}

All variables and parameters are final

It's like I said. I don't believe in myself (don't accidentally overwrite my value). That being said, I don't believe in myself because ...

... That's why all the variables and parameters are final.

Bad
void input (String importantmessage) {
String answer = "...";
Answer = Importantmessage = "LOL accident";
}
Good
Final void input (final String importantmessage) {
Final String answer = "...";
}

Do not trust generics when overloaded

Yes, it can happen. You believe that you write the super nice API, it is very intuitive, followed by some users who just convert the original type to object type, until the damned compiler stops complaining, and suddenly they will link the wrong way, thinking this is your error.

Look at the following code:

// Bad
<T> void Bad (T value) {
Bad (collections.singletonlist (value));
}
<T> void Bad (list<t> values) {
...
}
//Good
final <T> void Good (final T value) {
if (value instanceof List)
Good ((list<?>) value);
Else
Good (collections.singletonlist (value));
}
final <T> void Good (final list<t> values) {
...
}
because, you know ... Your users, they're like

This library sucks
@SuppressWarnings ("All")
Object T = (object) (List) arrays.aslist ("abc");
Bad (t);
Believe me. I've seen it all. Include the following

This paranoia is still good.

Always throws an exception in the default of the switch statement

Switch statement ... One of their ridiculous statements I don't know whether to be in awe or cry, but anyway, since we stick with switch, we might as well use it perfectly to see the following code:

// Bad
switch (value) {
Case 1:foo ();
Case 2:bar ();
}
//Good
switch (value) {
Case 1:foo ();
Case 2:bar ();
Default:
throw new Threaddeath ("that ' ll teach them");
}
when value = = 3 o'clock, there will be a hint that can not be found, and will not let people know so.

Switch statement with curly braces

In fact, switch is the most evil statement, like some people who are drunk or lose a bet to write code, look at the following example:

//bad, doesn ' t compile
switch (value) {
Case 1:int j = 1;
Case 2:int j = 2;
}
//Good
switch (value) {
Case 1: {
final Int j = 1;
Break ;
}
Case 2: {
final Int j = 2;
Break ;
}
//Remember:
Default:
throw new Threaddeath ("that ' ll teach them");
}
In a switch statement, each CASE statement has a range of only one line of statements, in fact, these case statements are not even real statements, they are like jump tags in a goto statement.

Conclusion

Paranoid programming seems incredible, sometimes, because code is often proven to be more detailed, but not required. You might think, "Oh, this is never going to happen", but as I said. After about 20 years of programming, you don't want to fix only these stupid bugs, because the programming language is so old and flawed. Because you know ...

It's up to you now! What are your most paranoid quirks in programming?

Reprint: 10 Practical But paranoid Java programming techniques

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.