Paranoid, but it works. 10 Java Programming Tips

Source: Internet
Author: User

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

Preventing accidental nullpointerexception is never a bad idea by placing string constants on the left side of the comparison function equals () comparison, like this:

Java code
    1. Bad
    2. if (Variable.equals ("literal")) {...}
    3. Good
    4. if ("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:

Java code
    1. string[] files = file.list ();
    2. Watch out
    3. if (Files! = null) {
    4. For (int i = 0; i < files.length; i++) {
    5. ...
    6. }
    7. }


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:

Java code
    1. if  (file.isdirectory ())  {  
    2.     string[] files = file.list ();   
    3.     
    4.     //&NBSP;WATCH&NBSP;OUT&NBSP;&NBSP;
    5.     if  (files != null)  {  
    6.          for  (int i = 0; i  < files.length; i++)  {  
    7.              ...  
    8.          }  
    9.     }  
    10. }  


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

3. Do not Believe "-1"

I know it's paranoid, Javadoc's early description of String.IndexOf () is 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 can be taken for granted, right? I said wrong, look at this:

Java code
    1. Bad
    2. if (String.IndexOf (character)! =-1) {...}
    3. Good
    4. if (String.IndexOf (character) >= 0) {...}


Who knows. Perhaps in a particular situation they will need another encoding value, if not case-sensitive, otherstring will be included in ... Maybe you can return 2 at this point? Who knows.

After all, we have a lot of discussion about the null--value of billions of dollars in errors. Why not start the discussion-1, in a sense-1 is another form of NULL under the int type.

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)

Java code
    1. Ooops
    2. if (variable = 5) {...}
    3. Better (because causes an error)
    4. if (5 = variable) {...}
    5. Intent (remember. Paranoid JavaScript: = = =)
    6. 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.

Java code
    1. Bad
    2. if (Array.Length > 0) {...}
    3. Good
    4. if (array! = null && 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 strictly final. You can view the # # of 10 subtle best practices in our Java coding.

Java code
    1. Bad
    2. Public void Boom () {...}
    3. Good. Don ' t touch.
    4. 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 variables and parameters are declared in final.

Java code
    1. // bad  
    2. void input (string importantmessage)  {  
    3.     string answer = 
    4.    
    5.     answer = importantmessage =  "LOL  Accident ";   
    6. }  
    7.    
    8. / / good  
    9. final void input ( final string importantmessage)  {  
    10.     final string answer = 
    11. }  


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 Val directly to represent variables, not even variability, unless they explicitly need them to declare variables with VAR, but this is especially rare.

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:

Java code
  1. Bad
  2. <T> void Bad (T value) {
  3. Bad (collections.singletonlist (value));
  4. }
  5. <T> void Bad (list<t> values) {
  6. ...
  7. }
  8. Good
  9. Final <T> void Good (final T value) {
  10. if (value instanceof List)
  11. Good ((list<?>) value);
  12. Else
  13. Good (collections.singletonlist (value));
  14. }
  15. Final <T> void Good (final list<t> values) {
  16. ...
  17. }


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

Java code
    1. This library sucks
    2. @SuppressWarnings ("all")
    3. Object T = (object) (List) arrays.aslist ("abc");
    4. 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:

Java code
  1. Bad
  2. Switch (value) {
  3. case 1:foo ();  Break ;
  4. case 2:bar ();  Break ;
  5. }
  6. Good
  7. Switch (value) {
  8. case 1:foo ();  Break ;
  9. case 2:bar ();  Break ;
  10. Default:
  11. throw New Threaddeath ("that ' ll teach them");
  12. }


Because when value=3 is introduced into the software, the default will work, making it work! Don't mention the enum type to me, as this applies to enums as well.

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

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

Java code
  1. Bad, doesn ' t compile
  2. Switch (value) {
  3. case 1: int j = 1;  Break ;
  4. Case 2: int j = 2;  Break ;
  5. }
  6. Good
  7. Switch (value) {
  8. Case 1: {
  9. final Int j = 1;
  10. Break ;
  11. }
  12. Case 2: {
  13. final Int j = 2;
  14. Break ;
  15. }
  16. //Remember:
  17. Default:
  18. throw New Threaddeath ("that ' ll teach them");
  19. }


In the switch statement, only one scope is defined for all the case. In fact, these are not real-world statements, they are more like tags, and switch is a goto statement that points to those tags. In fact, you can even compare case statements with amazing FORTRAN77 declarations, and for FORTRAN, its mystique has transcended its function.

This means that the variable final int J can be accessed by any case, whether or not we have a break. It doesn't look very intuitive. We can create a new nested scope for each case by adding simple curly braces, 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

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.