10 Practical But paranoid Java programming techniques

Source: Internet
Author: User
Tags case statement

After indulging in coding for a while (say I've been on the program for almost 20 years), you're getting used to these things. Because, you know ...

Anything can go wrong, yes, it does.

That's why we're using defensive programming, the reason for some paranoid habits. Here are 10 of the most useful but paranoid Java programming techniques I personally think of. Let's take a look: 1. Put a string string in the front

To prevent accidental nullpointerexception exceptions, we usually place a string on the left side of the Equals () function to implement the strings comparison, as follows:

Bad
if (variable.equals ("literal")) {...}
Good
if ("literal". Equals (variable)) {...}

This is what you can do with your brain, from the bad version of the code rewrite the expression to the good version of the code, there is no loss of anything in between. Welcome to different viewpoints ... 2. Do not trust the early JDK APIs

In the early days of Java, programming was a very painful thing. Those APIs are still immature, and you may have encountered the following code block:

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

It looks paranoid. Maybe, but please look at Javadoc:

If the virtual path does not represent a folder directory, this method returns NULL. Otherwise, an array of strings will be returned, each representing the files or folders in the directory.

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

if (File.isdirectory ()) {
    string[] files = file.list ();
    Watch out
    if (the files!= null) {for
        (int i = 0; i < files.length; i++) {
            ...
        }
}}
3. Do not Believe "-1"

I know it's paranoid, but in Javadoc the String.IndexOf () method explicitly states that the first occurrence of the specified character's positional index within an object, or 1, indicates that the character is not in a sequence of characters.

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

Bad
if (string.indexof (character)!=-1) {...}
Good
if (string.indexof (character) >= 0) {...}

who knows. Maybe then they change the encoding, the string is not case-sensitive, and perhaps the better way is to return-2. Who knows. 4. Avoid accidental assignment

Yes. This kind of thing may happen often.

Ooops
if (variable = 5) {...}
Better (because causes an error)
if (5 = variable) {...}
Intent (remember. Paranoid JavaScript: = = =
if (5 = = variable) {...}

so you can place the comparison constants on the left side so that there is no unexpected assignment error. 5. Check null and length

Anyway, as long as you have a collection, an array, and so on, 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. 6. All the methods are final .

You may tell me your open/closed principle, but it's all nonsense. I don't believe in you (inherit all the subclasses of my parent class correctly), nor do I believe in myself (accidentally inheriting all subclasses of my parent class). So for those that have a definite meaning, use the final logo strictly.

Bad public
void Boom () {...}
Good. Don ' t touch.
Public final void Donttouch () {...}
7. All variables and parameters are final

Just like I said. I don't believe in myself (don't accidentally overwrite my values). 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 = "...";} 
8. Do not trust generics when overloading

Yes, it can happen. You believe that you write the Super good-looking API, it's intuitive, and then, some users who just convert the original type to object type until the damned compiler stops whining and suddenly they link the wrong way, thinking it's your fault.

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); C12/>else
        Good (collections.singletonlist (value));
}
Final <T> void Good (final list<t> values) {
    ...
}

Because, you know ... Your users and they're like

This library sucks
@SuppressWarnings ("All")
Object t = (object) (List) arrays.aslist ("abc");
Bad (t);

Believe me. I have seen all this. including the following

This paranoia is still good. 9. Always throw an exception in the default of a switch statement

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

Bad
switch (value) {case
    1:foo ();
    Case 2:bar (); break;
Good
switch (value) {case
    1:foo ();
    Case 2:bar (); break;
    Default:
        throw new Threaddeath ("that ll teach them");
}

when value = = 3 o'clock, there will be a hint that cannot be found, not to be known. 10.Switch statement with curly braces

In fact, switch is the most vicious statement, like some people who are drunk or losing a bet are writing code, look at the following example:

Bad, doesn ' t compile
switch (value) {case
    1:int j = 1;
    Case 2:int j = 2; break;
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, the scope of each case statement is only one line of statements, in fact, these case statements are not even real statements, they are like jump tags in a goto statement. Conclusions

Paranoid programming may seem inconceivable, 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 just these stupid bugs, because the programming language is so old and flawed. Because you know ...

Now it's up to you. What is your most paranoid quirk in programming. Translation Links: http://www.codeceo.com/article/10-useful-paranoid-java-coding.html
Top useful, yet paranoid, Java programmer techniques
Translation Author: Code Rural network – Xiao Feng

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.