Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the practical but paranoid Java programming techniques

2025-03-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Today, I will talk to you about the practical but paranoid Java programming techniques, which may not be well understood by many people. in order to make you understand better, the editor has summarized the following content for you. I hope you can get something according to this article.

After indulging in coding for a while, you will get used to these things.

Anything can go wrong, yes, it is.

This is why we should adopt "defensive programming", that is, some paranoid habits. Here are my 10 most useful but paranoid Java programming techniques. Let's take a look:

1. Put the String string first

To prevent occasional NullPointerException exceptions, we usually place String to the left of the equals () function to achieve string comparison, as shown in the following code:

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

This is something you can do with your head, from the Bad version of the code to the Good version of the code without losing anything in between. Different views are welcome.

two。 Don't trust the early JDK API.

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

String [] files = file.list (); / / Watch out if (files! = null) {for (int I = 0; I)

< files.length; i++) { ... } } 看上去很偏执?也许吧,但请看Javadoc: 如果这个虚拟路径不表示一个文件夹目录,则此方法返回null。否则将会返回一个字符串数组,每一个字符串表示目录中的文件或文件夹。 对,没错。我们可以添加一些校验: if (file.isDirectory()) { String[] files = file.list(); // Watch out if (files != null) { for (int i = 0; i < files.length; i++) { ... } } } 3.不要相信"-1" 我知道这是偏执的,但Javadoc中对 String.indexOf()方法明确指出:对象内***次出现指定字符的位置索引,如果为-1则表示该字符不在字符序列中。 所以使用-1是理所当然的,对吗?我说不对,请看以下代码: // Bad if (string.indexOf(character) != -1) { ... } // Good if (string.indexOf(character) >

= 0) {.}

Who knows. Maybe then they will change the way they encode so that strings are not case-sensitive, maybe it would be better to return-2? Who knows.

4. Avoid accidental assignment

Right. This may happen all the time.

/ / 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 so that there is no accidental assignment error.

5. Check Null and Length

In any case, as long as you have a collection, 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, maybe from earlier versions of JDK API, who knows.

6. All the methods are final.

You may tell me your open / close principle, but it's all nonsense. I don't trust you (inheriting all the subclasses of my parent class correctly), and I don't believe in myself (accidentally inheriting all the subclasses of my parent class). Therefore, for those methods with clear meaning, we should strictly use final identification.

/ / Bad public void boom () {.} / / Good. Don't touch. Public final void dontTouch () {...}

7. All variables and parameters are final

Like I said. I don't believe in myself (don't accidentally overwrite my value). Having said that, I don't believe my own because...

... This is why all 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. Don't trust generics when overloaded

Yes, it can happen. You believe in the super good-looking API you wrote, and it's intuitive, followed by some users who just convert the primitive type to the Object type until the damn compiler stops whining, and suddenly they will link to the wrong method, thinking it's your fault.

Look at the following code:

/ / Bad void bad (T value) {bad (Collections.singletonList (value));} void bad (List values) {.} / / Good final void good (final T value) {if (value instanceof List) good ((List) value); else good (Collections.singletonList (value));} final void good (final List 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 all this. Including the following

This kind of paranoia is not bad.

9. Always throw an exception in the Default of a Switch statement

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

/ / Bad switch (value) {case 1: foo (); break; case 2: bar (); break;} / / Good switch (value) {case 1: foo (); break; case 2: bar (); break; default: throw new ThreadDeath ("That'll teach them");}

When value = = 3, there will be a hint that cannot be found without letting people know what it means.

10.Switch statement with curly braces

In fact, switch is the most evil sentence, like some people who are writing code when they get drunk or lose a bet. Take a look at the following example:

/ / Bad, doesn't compile switch (value) {case 1: int j = 1; break; 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 switch statements, 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 markers in goto statements.

Paranoid programming may seem incredible, sometimes, because the code often turns out to be a little more detailed, but not required. You might think, "Oh, that's never going to happen," but like I said. After 20 years or so of programming, you don't want to just fix these stupid bug, because the programming language is so old and flawed.

After reading the above, do you have any further understanding of practical but paranoid Java programming techniques? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report