Null is your firend, not a mistake

Original author: Roman Elizarov

Original Address: Null IS your firend, not A Mistake

Translator: Bing heart says

Kotlin Island from Wikimedia by Pavlikhin, CC BY-SA 4.0

I use the Java programming language has been a long long time, mastered by software written in Java and maintaining large (millions of lines of code) should pay attention to what, and witnessed the whole industry is struggling to avoid null pointer exception NullPointerException(NPE), it is plagued by large and small Java class libraries. In 2009, its inventor Tony Hoareadmits he caused a null reference is the "billion-dollar mistake" Before, everyone has been aware of its danger.

In the year 1996 Java 1.0 release, this problem is not so obvious. Let's look at a typical Java API examples: File.list()method. It is used to include the contents of the folder, as follows:

for(String name : new File("directory").list()) {
    System.out.println(name);
}

Only if the folder exists above code will run properly, or they will be thrown NPE, because list()returns null. But who would write such a code? Not only list()to documentation clearly explains what is returned when the folder does not exist null, and modern IDE will give you a warning for a particular code.

However, when using the Java programming, developers often commit such mistakes. So far, a large number of studies have shown how they occurred. The results show that, in most cases, our API function should not return null, other developers also do not want to return null. In some special cases, such as defaults, Java in the convention is to return some "empty object" (empty set, unfilled objects, etc.), or throw an exception, worse than return null. This is why the design Files.newDirectoryStream, advanced version of File.listany case will not appear null.

So when null in some special cases as a function of the return value, such as performance optimization, uninitialized reference field and so on, it will often surprise you, not ready to deal with it. Not only must deal with null values ​​rarely the case, and the code used to handle null values ​​in Java is a very long-winded:

String[] list = new File("directory").list();
if (list != null) {
    for (String name : list) {
        System.out.println(name);
    }
}

No doubt, unless really need (your customers in a production environment found NPE), or you really do not want to write code.

Fear of null results in some extreme cases. There are some Java coding style total ban null, the hateful work to developers. Do not know if you have seen such a Java class libraries, all domain objects must implement a special Nullinterface, and provide examples of hand-coding the generated "empty object." If you show that you have not seen or lucky. But I bet you've seen only in order to avoid contamination null and Java code Optional <T>wrapper (Translator's Note: Java 8 new features).

Some set of API framework for prudential prohibit null elements, and some of Java's core team members believe the Java Collections Framework support for null is a mistake. It makes very sad.

In fact, this null concept is not a mistake, but the Java type system is considered null members of any type. Let's see, in Java “abc”is a legitimate String, nullis a legitimate String. You can use all the methods of string on the former, for example substring. But the use of run-time error occurs on the latter. It is safe to type it? Not exactly. Abnormalities (e.g. except 0) is normal, but when a value of all operations of this type have undergone abnormal operation occurs during a certain operation of a particular type of value, which is the first indicated value does not belong to this type. All those NPE show the existence of obvious defects Java type system.

More type-safe programming language such as Kotlin, through reasonable to merge the concept of null type system to repair this defect. Adding checks and warnings also have a role, but that is not enough. Obviously, a type of sound system must allow Stringthe type of all variables to support its operations. So in Kotlin, the nullassigned Stringvariable of that type is not just a warning, but rather the type of error, as the value 42assigned to Stringthe type of variable the same.

Type system in a reasonable null API support is a turning point in the design, there is no reason to be afraid to go to a null. Some functions return a nullable type String?, other types of function return is not empty String, it is returned and some of the functions String, and others return Intthe same. They are of different types, but has a different set of operations security.

Safety of type null to mean "missing value" is better, more efficient, more concise. Look at the Kotlin standard library String.toIntOrNull()functions for string converted to digital, can not be converted, then return null. Very pleasant to use, write a command line program, lack of acceptance of integer parameters and process parameters is very simple:

fun main(args: Array<String>) {
    val id = args.getOrNull(0)?.toIntOrNull() 
        ?: error("id expected")
    // ...
}

Null use it in API design, it is your good friend and Kotlin. There is no reason to be afraid of it, there is no reason to use the null objectmodel or package to handle it, not to mention the anomaly. Rational use of null in your API will give you bring more readable, more secure code, and away from the boilerplate code.

Further Reading

If you like this theme, and want to know more details about language design, consider reading this article - Dealing with Absence of value .

Articles starting micro-channel public number: 秉心说focused Java, Android original knowledge sharing, LeetCode problem solution.

More recent original articles, scan code concerned about me!

Guess you like

Origin www.cnblogs.com/bingxinshuo/p/11546151.html