10 Practical But paranoid Java programming techniques

Source: Internet
Author: User
Tags case statement

1. Place string strings at the front

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

<pre http:= "" www.ahlinux.com= "" start= "" cmd= "" 9034.html "=" target= "_blank" class= "Keylink" style= "margin:15px Auto padding:10px 15px; font-size:16px; line-height:30px; Word-break:break-all; Word-wrap:break-word; ">rmal; line-height:20px; Font-family: ' Courier New '; border-width:1px 1px 1px 4px; Border-style:solid; Border-color:rgb (221, 221, 221); Color:rgb (68, 68, 68); BACKGROUND:RGB (251, 251, 251); " >//Badif (variable.equals ("literal")) {...} Goodif ("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 ...

2. 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 outif (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++) {            ...        }}    }
3. Do not 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:

Badif (String.IndexOf (character)! =-1) {...} Goodif (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.

4. Avoid accidental assignment of values

Yes. This kind of thing may often happen.

Ooopsif (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.

5. Check null and length

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

Badif (Array.Length > 0) {...} GOODIF (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 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.

badpublic void Boom () {...} Good. Don ' t touch.public final void Donttouch () {...}
7. 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.

Badvoid input (String importantmessage) {    string answer = "...";    Answer = Importantmessage = "LOL accident";} goodfinal void input (final string importantmessage) {    final string answer = "...";}
8. 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) {    ...} Goodfinal <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.

9. Always throw 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:

Badswitch (value) {case    1:foo ();    Case 2:bar (); break;} Goodswitch (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 can not be found, and will not let people know so.

10.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 compileswitch (value) {case    1:int j = 1;    Case 2:int j = 2; break;} Goodswitch (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.

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.