Java basic learning Summary (127) -- the Java method should return null objects or null, javanull

Source: Internet
Author: User

Java basic learning Summary (127) -- the Java method should return null objects or null, javanull
Should the Java method return null or null?In most cases, an empty object (empty object) is used in the method to return a value instead of null. The reason is very simple. Empty objects are the same as other meaningful objects, so that users who call methods do not need to differentiate the return values, that is, they do not need to determine whether the return value is null, this simplifies the client call (if judgment is not required before the return value is used). In addition, it makes the client code more error-prone (if a careless programmer or forgets to judge null ).
I think this is a very tangled problem. The project I am working on is suffering from this problem. In the current project, almost all methods (created in the project) use the null return type, whether it is a String or a collection class.
For example:
List <User> getUsers (){
If (! Validation ()){
Return null;
} // Return a ArrayList containing logic data
}
In this way, all the places where this method is used must be null before the return value is used,
For example, before a for loop, such as before retainAll (), or before size. This is not the most painful. the most painful thing is that not all methods return null. In some cases, an empty ArrayList is returned. Some of these methods are within the project,
Some are third-party class libraries. Therefore, in order to be robust, No matter 3X7 = 21, for the return value of any method, null is first judged before use, god knows if other people will change the return value of the method from an empty object to null in the next minute.
Therefore, a large number of if statements can be seen as soon as the code is opened. if they are mixed with some conditional statements and for statements, it is a disaster. So how should we face this problem? Where should null be returned, and where should null objects be returned?
1. For collections and arrays as return values, use an array or set with zero length instead of null. There are too many advantages:
A. Simplified code. The caller does not need to judge null before using the returned value. No matter size (), for (), set operations are OK.
B. Enhance program robustness. Since the return value is not null, you don't have to worry about the ubiquitous NullPointer exception. Opponents generally think from the performance perspective that this increases the overhead of the system. I think this is quite interesting,
I have seen many programmers write some bad designs, such as bad Exception Handling and algorithm loops, but they are very concerned about this empty set. I personally don't have a high sense of performance. I think for cainiao like me who barely guarantees program robustness,
Too much consideration of performance issues is impractical. Not only do I not have that ability, but it is very likely that I will make things worse. It is unwise to worry about performance issues at this level by using the valid Java book, unless the analysis shows that this method is the real source of performance problems.
In addition, he mentioned that we can return reusable empty objects in the program, such as an array with zero length or emptyList/emptySet (which are defined in the Collections class, in our entire program cycle, only this empty object will be allocated.
Of course, there is a problem here. If you want to modify the returned List in the future,
For example:
List <User> users = getUsers ();
Users. add (user );
It is unreasonable to return Collections. emptyList (). The whole empty set cannot be modified. It is not an ArrayList or empty List, but an implementation of the List interface.
2. Use a string as the return value. Use a null string instead of null. We often have methods to return strings. In many cases, we concatenate strings or perform equals or split operations. If the returned value is null, we must make null judgments. For String concatenation,
The NullPointer exception will not be reported, but it will be used as "null", which is even more strange. Example: String a = null; String B = a + "B"; // result: nullB
3. Any logical representation of search (or get) should return null. For example, the following method is unreasonable: User getUserById (String id) {User user = dao. getUserById (id); if (user = null) return new User (); return user ;}
4. When an empty object has the same behavior and meaning as other returned objects, use an empty object. For example, there is a method to return an iterator. An empty Iterator can be defined as NullIterator and implements the Iterator interface. Its next method always returns null,
The hasNext method always returns false. In this way, the code that uses this method to return values should not be null, because NullIterator acts the same way as other iterators. It is not enough to talk about how to use it. For projects, project constraints are also required to restrict developers' behaviors. Otherwise, it is a mess because no one believes in it. View comments

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.