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

How to remove the annoying "! = null" from the Java code

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >

Share

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

This article is about how to get rid of the annoying "! = null" in the Java code. The editor thinks it is very practical, so I share it with you. I hope you can get something after reading this article.

problem

To avoid null pointer calls, we often see statements like this

If (someobject! = null) {

Someobject.doCalc ()

}

In the end, there will be a lot of null code in the project, how ugly and cumbersome! How to avoid this situation? Have we abused the empty judgment?

Answer

This is a problem that beginners and intermediate programmers often encounter. They always like to return null in methods, so they also have to call null when calling these methods. In addition, perhaps affected by this habit, they subconsciously think that all returns are untrustworthy and add a lot of empty judgments in order to protect their programs.

After complaining, let's go back to the topic itself and make an unprecedented judgment. Please distinguish between the following two situations:

Null is a valid and meaningful return value (Where null is a valid response in terms of the contract; and)

Null is invalid and incorrect (Where it isn't a valid response.)

You may not understand the meaning of these two sentences, take your time, move on, and then we will discuss these two situations in detail.

Let's start with the second case.

Null is an unreasonable parameter, so you should explicitly interrupt the program and throw an error. This situation is common in the api method. For example, if you develop an interface, id is a required parameter. If the caller does not pass this parameter to you, of course not. You need to be aware of the situation and tell the caller, "Hey, man, what are you doing sending me a null?"

There are two better ways to check than null statements.

Assert statement, you can put the cause of the error in the parameter of assert, which not only protects your program from going down, but also returns the cause of the error to the caller, which is killing two birds with one stone. (the original text introduces the use of assert, which is omitted here)

You can also throw a null pointer exception directly. As mentioned above, null is an unreasonable parameter at this time. If there is a problem, it should be thrown out generously.

The first situation will be more complicated.

In this case, null is a "seemingly" reasonable value. For example, when I query a database, there is no corresponding value under a certain query condition, and null expresses the concept of "empty".

Here are some practical suggestions:

If the return type of the method is collections, you can return an empty collections (empty list) instead of null when the return result is empty. In this way, the calling side can boldly handle this return, for example, after the calling side gets the return, it can directly print list.size () without worrying about null pointers. (what? When you want to call this method, you don't remember if you followed this principle when you implemented it before? So code habits are important! If you get into the habit of writing code like this (returning empty collections instead of null), you can boldly ignore null when you call your own method.

What if the return type is not collections?

Then return an empty object (instead of a null object). Here is a "chestnut", assuming the following code

Public interface Action {

Void doSomething ();}

Public interface Parser {

Action findAction (String userInput);}

Among them, Parse has an interface, FindAction, which finds and executes the corresponding action based on the user's input. If the user types incorrectly, the corresponding action (Action) may not be found, so findAction returns null, and the next time action calls the doSomething method, a null pointer appears.

One way to solve this problem is to use Null Object pattern (empty object pattern).

Let's transform it.

The class is defined as follows, so when the findAction method is defined, make sure that no null object is returned no matter what the user enters:

Public class MyParser implements Parser {

Private static Action DO_NOTHING = new Action () {

Public void doSomething () {/ * do nothing * /}

}

Public Action findAction (String userInput) {

/ /...

If (/ * we can't find any actions * /) {

Return DO_NOTHING

}

}

}

Compare the following two call examples

1. Redundancy: each time an object is obtained, it is judged to be null.

Parser parser = ParserFactory.getParser ()

If (parser = = null) {

/ / now what?

/ / this would be an example of where null isn't (or shouldn't be) a valid response

}

Action action = parser.findAction (someInput)

If (action = = null) {

/ / do nothing}

Else {

Action.doSomething ()

}

two。 Simplify

ParserFactory.getParser (). FindAction (someInput). DoSomething ()

Because an empty object is not returned in any case, you can safely call the method of action after you get the action through findAction. An extension: Java: how to handle null values more elegantly?

Other selected answers: if you want to use the equal method, please use object.equal (object))

For example:

Use

"bar" .equals (foo)

Instead of

Foo.equals ("bar")

In Java8 or guava lib, the Optional class is provided, which is an element container that encapsulates objects and reduces null detection. But there is still a lot of code. I'm not happy.

If you want to return to null, stop and think about whether this place should throw an exception.

The above is how to remove the annoying "! = null" from the Java code. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.

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

Internet Technology

Wechat

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

12
Report