Paranoid, but it works. 10 Java Programming Tips

Source: Internet
Author: User

This article is translated by Importnew-lynnshaw from Javacodegeeks. Welcome to join the translation team. Reproduced please see at the end of the request.

After a period of coding (gee, I've been through almost 20 years of programming, Happy days are always going fast), we're starting to appreciate those good habits. Because, you know ...

"Anything that could go wrong will go wrong in the end." ”

That's why people like to do "error-proof programming." Paranoid habits sometimes make sense, and sometimes they're not clear enough or smart enough, and maybe it's a little weird when you think of someone who writes like that. Here are 10 of the most useful and paranoid Java programming techniques I've listed for personal feeling. Please see:

1. Put string constants in front

By placing string constants on the left side of the comparison function equals() comparison item NullPointerException  , it is never a bad idea to prevent accidental, like this:

//  Bad if (Variable.equals ("literal"//  goodif ("literal". Equals (variable)) {...}

There is no doubt that converting one expression to another is a better expression without losing anything. As long as our Options are real (optional in Java 8 is an encapsulation of objects that can be empty), right? Discuss ...

2. Don't trust the early JDK APIs

Java just appeared, programming must be a very painful thing. The API was still immature, and you might have encountered a piece of code like this:

string[] files =//  Watchoutifnull) {    for (  int i = 0; i < files.length; i++) {        ...    }}

It looks strange, doesn't it? Maybe, but look at this Javadoc:

"If the abstract pathname represents not a directory, then this method returns NULL." Otherwise, a string array is returned, where each string represents a file or directory under the current directory. ”

Yes, it is best to add an empty check to ensure that it is correct:

if (File.isdirectory ()) {    = file.list ();      // Watch out    if NULL {        for (int i = 0; i < files.length; i++) {            ...}}    } 

Bad! The former violates the rules of 10 subtle best practices in Java coding, # # and #. So be sure to remember to null check!

3. Do not Believe "-1"

I know it's paranoid, Javadoc's String.indexOf() early description is like this ...

"The first occurrence of a character in a sequence of characters will be returned as a result, or 1 if the character does not exist." ”

So, -1  it can be taken for granted, right? I said wrong, look at this:

//  Bad if (String.IndexOf (character)! =-1//  goodif (String.IndexOf (character) >= 0) { ... }

Who knows. Perhaps they will need another coded value in a particular situation, if not case sensitive, it will be included in ... otherString Maybe you can go back now -2呢 ? Who knows.

After all, we have a lot of discussion about the null--value of billions of dollars in errors. Why don't you start talking about -1呢, a sense -1 of nullint类型下的另一种形式。

4. Avoid accidental assignment

Yes. Even the best programmers can make this mistake (not me, of course.) See # #).

(Assuming this is JavaScript, we are paranoid that this is the language)

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

Say it again. If there is a constant in your expression, place it on the left side of the equation. So when you're going to add another =, it's not easy to go wrong.

5. Check for null and length

Whenever you have a collection, an array, or something else, make sure it exists and is not empty.

//  Bad if (Array.Length > 0//  goodifnull && array.length > 0) { ... }

You don't know where these arrays come from, perhaps the early JDK API?

6. All methods are declared in final

You can tell me any opening and closing principle you want, but that's nonsense. I don't believe you (can inherit my class correctly), nor do I trust myself (not accidentally inheriting my class). Therefore, all but the interface (specifically for inheritance) should be strict final . You can view the # # of 10 subtle best practices in our Java coding.

//  Bad  Public void  //  good. Don ' t touch.  Public Final void Donttouch () {...}

Yes, written final. If this doesn't make sense to you, you can also change the class and method by modifying or rewriting the bytecode, or sending a feature request. I'm sure it's not a good idea to rewrite the class/method.

7. All variables and parameters are declared with final

It's like I said. I don't believe that I don't accidentally rewrite a value. So, I really don't believe in myself at all. Because:

This is why all the variables and parameters are used final声明的原因 .

 //  bad    input (string importantmessage) {string answer  =" ... "; Answer  = Importantmessage = "LOL accident" ;}  //  good  final  void  input (final   String Importantmessage) { final  String answer = "..." ;}  

Well, I admit, I'm not used to this one myself, although I should use it. I want Java to be like the Scala language , where people use it all the time, val 来表示变量 not even the variability, and unless they explicitly need it, they use Var to declare variables, but that's a very rare opportunity.

8. Do not trust generics when overloaded

Yes, this is going to happen. You think you've written a great API, it's really cool and intuitive, and then there's a bunch of users who just mechanically all types into Object until the damned compiler stops working, and then they suddenly link to the wrong method, thinking it's all your fault (it always is).

Think about this:

// Bad<T>voidBad (T value) {Bad (collections.singletonlist (value));}<T>voidBad (list<t>values) {    ...} //GoodFinal<T>voidGood (FinalT value) {    if(Valueinstanceoflist) Good ((list<?>) value); ElseGood (collections.singletonlist (value));} Final<T>voidGood (FinalList<t>values) {    ...}

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

// This library sucks@SuppressWarnings (' all '= (Object) (List) arrays.aslist ("abc"); bad (t);

Believe me, I've seen a lot, and there's this.

So, it's good to be paranoid.

9. Always add default to the switch statement

Switch ... As one of the funniest expressions, I don't know whether to be in awe or to weep silently. Anyway, since we can't get rid of switch, we'd better be able to use it correctly when necessary, for example:

// BadSwitch(value) { Case1:foo (); Break;  Case2:bar (); Break;} //GoodSwitch(value) { Case1:foo (); Break;  Case2:bar (); Break; default:        Throw NewThreaddeath ("that ' ll teach them");}

because in when value=3  is introduced into the software, the default will be able to play a role to make it normal operation! Don't mention it to me enum 类型 , because it enums  works the same way.

10. Use curly braces to separate each case block of a switch

In fact, switch it is the most pit-father's statement that anyone who is drunk or loses a bet can use it in a language. Take a look at the following example:

//Bad , doesn ' t compileSwitch(value) { Case1:intj = 1; Break;  Case2:intj = 2; Break;} //GoodSwitch(value) { Case1: {        Final intj = 1;  Break; }     Case2: {        Final intj = 2;  Break; }     //Remember:    default:        Throw NewThreaddeath ("that ' ll teach them");}

in the switch statement, for all the case defines only one scope. In fact, these are case not real statements, they are more like labels, and they are switch goto statements that point to these tags. In fact, you can even compare the case statement with The amazing FORTRAN77 statement , for FORTRAN, its mystery has transcended its function.

This means that the variable final int j  can be accessed by any case, whether we have it or not break . It doesn't look very intuitive. We can create a new nested scope for each one by adding simple curly braces case , and of course don't forget to add a break at the end of each case's statement block.

Conclusion

Obsessive compulsive disorder in programming sometimes looks strange, making the code often more verbose than necessary. You might think, "Ah, this situation never happens!" "But, as I said, after 20 years of programming, you don't want to fix stupid and unnecessary bugs that are simply the result of the old and inherent flaws in the programming language." Because you know .....

https://youtu.be/oO3YmT2d-8k

Now, it's your turn!

Paranoid, but it works. 10 Java Programming Tips

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.