1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > [转载] java避免空指针异常_第1部分:在现代Java应用程序中避免空指针异常

[转载] java避免空指针异常_第1部分:在现代Java应用程序中避免空指针异常

时间:2018-08-03 23:34:35

相关推荐

[转载] java避免空指针异常_第1部分:在现代Java应用程序中避免空指针异常

参考链接: Java的instanceof及其应用

java避免空指针异常

空做与不做 (Null do’s and don’ts)

In the talk Null References: The Billion Dollar Mistake, Sir Tony Hoare describes implementing null references as a part of the ALGOL programming language, as well, a billion-dollar mistake. Authoritative programming books like Clean Code: A Handbook of Agile Software Craftsmanship advise you to use null as little as possible, while the book Bug Patterns In Java dedicates three whole chapters to problems stemming from null-values. The StackOverflow topic “What is a null pointer exception and how do I fix it” has 3 million views. It is easy to get anxious working with null-values!

在演讲“ 空引用:十亿美元的错误”中 ,Tony Hoare爵士描述了将空引用作为ALGOL编程语言的一部分以及十亿美元的错误。 权威编程书籍喜欢干净代码:敏捷软件Craft.io的手册建议你使用零尽可能少,而这本书的错误模式在Java致力于整整三章从空值而引起的问题。 StackOverflow主题“ 什么是空指针异常以及如何解决它 ”有300万个视图。 急于使用空值很容易!

I’m not one to tell Turing-award winners like Hoare how to design programming languages, but I will say that I don’t think null is inherently bad. I will discuss why that is, when you should and shouldn’t use null, and how to elegantly handle null-values over in the following two blog posts. In the current post, I will present my musings on using null values and in the next blog post (going online Friday 21st August), we’re going to look at the practical application of some techniques for working with null, including recent features in Java 8.

我不是要告诉像Hoare这样的图灵奖获奖者如何设计编程语言,但是我会说,我认为null并不是天生就不好的。 我将在以下两篇博客文章中讨论为什么这样做,何时不应该使用null,以及如何优雅地处理null值。 在当前文章中,我将介绍有关使用null值的想法,在下一篇博客文章(8月21日,星期五在线)中,我们将研究一些使用null的技术的实际应用,包括Java 8。

While the posts are Java-centric, the underlying principles and discussion should extend to object-oriented programming languages in general. The blog posts are primarily intended for less experienced programmers and anybody else who might be intimidated by null, but old dogs might learn some new tricks too.

尽管这些帖子是以Java为中心的,但总体而言,基本原理和讨论应该扩展到面向对象的编程语言。 该博客文章主要面向经验不足的程序员以及可能被null吓倒的其他任何人,但是老狗也可能会学习一些新技巧。

无效的危险 (The dangers of null)

Null is a special value as it is not associated with any type (feel free to verify with instanceof against every other class in the JRE) and will happily take the place of any other object in variable assignments and method calls. This is what gives null its two dangerous properties:

Null是一个特殊值,因为它不与任何类型关联(可以通过instanceof与JRE中的每个其他类进行验证),并且很乐意在变量赋值和方法调用中代替任何其他对象。 这就是使null具有两个危险特性的原因:

Every complex-typed return value may be null 每个复杂类型的返回值都可以为null Every complex-typed parameter value may be null 每个复杂类型的参数值都可以为null

As a result, any return value or parameter object is a NullPointerException (NPE) waiting to happen if not handled carefully.

结果,任何返回值或参数对象都是NullPointerException(NPE),如果不仔细处理就会等待发生。

Is the solution then to check every return value and parameter for null values? It should be obvious that this is a bad idea. First, it clutters the code with null-checks. Secondarily, it forces the developer to use precious time on considering the right way to handle null-values that never occurs, and the null-checks will mislead other developers.

那么解决方案是检查每个返回值和参数是否为空值吗? 很明显,这是一个坏主意。 首先,它使用空检查使代码混乱。 其次,它迫使开发人员花费宝贵的时间来考虑正确的方法来处理从未发生的空值,并且空检查会误导其他开发人员。

Is the solution to never assign null to any values? Well, no. As highlighted by the fact that most programming languages have the concept of an empty value (nil, undefined, None, void, etc), having a general value for nothing is tremendously useful.

解决方案是永远不要为任何值分配null吗? 好吧,不。 正如大多数编程语言都具有空值(nil,undefined,None,void等)这一事实所强调的那样,无所作为的通用值是非常有用的。

An error in a while-loop condition can create an infinite loop in any program, but it doesn’t make while-loops inherently bad. It would be similarly misguided to think that null is always bad just because misuse can lead to errors. Null is the most natural value to express certain things, but also a very poor value to express others. The competent developer must know when that is and isn’t. In the succeeding section, I will show you where that is.

while循环条件中的错误可以在任何程序中创建无限循环,但不会使while循环固有地变坏。 同样地,认为null总是很糟糕也仅仅因为滥用会导致错误,这是错误的。 空是表达某些事物的最自然的价值,也是表达其他事物的非常差的价值。 胜任的开发人员必须知道什么时候该是什么。 在接下来的部分中,我将向您展示该位置。

何时使用null,何时不使用null (When to use null and when not to)

In this part, I will examine the scenarios in which null are returned from and passed to methods, discuss some of the traditional alternatives (i.e. pre-Java 8) and argue why using a built-in empty type like null is the best solution in some cases.

在这一部分中,我将研究从方法返回null并将其传递给方法的场景,讨论一些传统的替代方法(即Java 8之前的版本),并说明为什么使用内置的空类型(如null)是最佳的解决方案,某些情况下。

返回null (Returning null)

One of the core philosophies of object-oriented programming is to model the concepts of the business domain in which our software operates. We do this by defining classes that correspond to these real-life concepts and their attributes. I think it’s meaningful to consider these types of classes separately from other types, when it comes to using null values.

面向对象编程的核心思想之一是为我们的软件在其中运行的业务领域的概念建模。 为此,我们定义了与这些现实概念及其属性相对应的类。 我认为在使用null值时,将这些类型的类与其他类型分开考虑是有意义的。

In the project I work on, the Columna electronic patient record system, we have classes that represent concepts in a hospital workflow, like patients, medications, physicians, hospital units, admissions, etc. As a part of modelling any domain, there are cases where we need to allow something to be nothing. For instance, assume that we have a class to represent an admission with attributes that describes the admission, like the hospital unit where the patient is admitted, the reason for admission, the time of admission, etc. Similarly, we might have a class that represents a patient that holds attributes like name and social security number. At any given point, a patient may or may not be admitted. More formally, we have a has-a relation with a cardinality of 0..1.

在我从事的项目Columna电子病历系统中,我们有代表医院工作流程中概念的类,例如患者,药物,医生,医院单位,住院等。作为对任何域建模的一部分,有一些案例在这里我们需要允许什么都不是。 例如,假设我们有一个类别来表示一个具有描述入场的属性的入场,例如入院患者的医院单位,入院原因,入院时间等。类似地,我们可能会有一个代表拥有姓名和社会保险号等属性的患者。 在任何给定的时间点,患者可能会或可能不会被接纳。 更正式地讲,我们具有基数为0.1的has-a关系。

Assume a method that retrieves admission information in a database for a given patient:

假设一种方法可以检索数据库中给定患者的入院信息:

public Admission getAdmission(Patient patient);

What should the method return for the patient who is not admitted if not null? Is there a more precise value to express this? I’d argue that there isn’t.

如果不为空,则该方法应返回给未入院的患者? 有没有更精确的价值来表达这一点? 我认为没有。

There are many other scenarios, where an object from the domain is directly associated with optional values as attributes. An object representing a medication holds values such as the medication name, the form of the medication, the strength, the active drug, etc. But medications are incredibly diverse, ranging from antibacterial creams to cannabis teas and not all of the attributes apply to each. Again, returning null for a missing attribute seems like an obvious choice to communicate that value is allowed to be missing. Is there a better alternative?

在许多其他情况下,域中的对象与可选值作为属性直接关联。 代表药物的对象具有诸如药物名称,药物形式,强度,活性药物等值。但是药物的种类繁多,从抗菌霜到大麻茶,并且并非所有属性都适用于每种药物。 同样,为缺少的属性返回null似乎是传达允许值丢失的明显选择。 有更好的选择吗?

Some advocate using the so-called Null Object design pattern instead of null. The basic idea is to implement a hollow class with none or little functionality — the null object — that can be used in place of the class that holds the actual functionality. The pattern is best exemplified with a scenario, where you must recursively traverse a binary tree data structure to find the sum of the value of each node. To do so, you essentially run a depth-first search and recursively sum the value of the left subtree with the right subtree in every node.

有人主张使用所谓的空对象 设计模式而不是null。 基本思想是实现一个没有任何功能或只有很少功能的空类(空对象),该空类可以代替拥有实际功能的类。 该模式最好以一种场景为例,在这种情况下,您必须递归遍历二叉树数据结构以找到每个节点的值之和。 为此,您实际上要进行深度优先搜索,然后在每个节点中递归将左子树的值与右子树的值相加。

A search tree is typically implemented such that every node in a search tree has a left and a right child that is either a node themselves or an empty leaf node. If the tree representation uses null for leaf notes, you will have to explicitly check for null children to stop recursing at a leaf node and to prevent trying to get the value of the node. Instead, you should define a Node interface with a simple getValue() method and implement it in the class representing a node that computes the value by summing the getValue() values of the children (see figure below). Implement the same interface in a class representing a node and let the leaf class return 0 when called. Now, we no longer have to distinguish code-wise between a leaf or a node; the need for an explicit check for null goes away and so does the risk of an NPE.

通常实现搜索树,以使搜索树中的每个节点都具有左右子节点,该子节点既可以是节点本身,也可以是空叶节点。 如果树表示形式对叶注释使用null,则必须显式检查是否有null子代,以停止在叶节点处递归并防止尝试获取该节点的值。 相反,您应该使用简单的getValue()方法定义一个Node接口,并在表示该节点的类中实现该接口,该节点通过将子代的getValue()值相加来计算值(请参见下图)。 在代表节点的类中实现相同的接口,并让叶类在调用时返回0。 现在,我们不再需要在叶或节点之间按代码区分; 显式检查是否为null的需求消失了,NPE的风险也消失了。

The Null object pattern applied to a tree structure

空对象模式应用于树形结构

To apply the pattern for the admission example above, we would need to create an Admission interface. We would then define an AdmissionImpl class for when we can return actual admission data and an AdmissionNullObjectImpl for when we can’t. This would allow the getAdmission()-method to return either the real AdmissionImpl or a AdmissionNullObjectImpl.As the calling code uses the shared Admission type, we can treat both objects the same with no risk of exceptions or without cluttering the code with checks for null handling.

要将模式应用到上面的准入示例,我们需要创建一个准入接口。 然后,我们将定义一个AdmissionImpl类(用于何时可以返回实际的准入数据),以及一个AdmissionNullObjectImpl(用于何时不能返回)。 这将允许getAdmission()方法返回真实的AdmissionImpl或AdmissionNullObjectImpl。由于调用代码使用共享的Admission类型,因此我们可以将两个对象视为相同,没有异常风险,也不会因检查null而使代码混乱处理。

However, I personally find it very hard to find usages for the pattern in typical production codebases, where the logic is often far more complex than a simple accumulation of numbers. Patterns exist to simplify solutions, but add complexity with no benefits when used inappropriately.

但是,我个人发现很难在典型的生产代码库中找到模式的用法,在这种代码库中,逻辑通常比简单的数字累加要复杂得多。 存在模式可以简化解决方案,但是如果使用不当,则会增加复杂性而没有任何好处。

What is the AdmissionNullObject class supposed to return when it doesn’t hold any real data? What should it return instead of a location object when getLocation() is called? What is the natural start date to return?

当AdmissionNullObject类不包含任何实际数据时应该返回什么? 调用getLocation()时,它应该返回什么而不是位置对象? 返回的自然开始日期是什么?

In many cases, you’d have to write code that at some point needs to check for something to handle fake values, so why not just have a null check in the first place and avoid defining extra complexity-increasing classes? There are cases where the pattern works great, but I feel they are rare in the real world, as it can only be used for objects with methods with void values or where you can return something that naturally fits into the flow of the surrounding code.

在许多情况下,您必须编写某些时候需要检查某些内容以处理假值的代码,那么为什么不首先进行空检查并避免定义额外的复杂性类呢? 在某些情况下,模式效果很好,但是我觉得它们在现实世界中很少见,因为它只能用于具有空值的方法的对象,或者可以返回自然适合周围代码流的对象。

Another alternative, which is sometimes used, is to use the empty string instead of null when an attribute is represented as a simple string. This removes the risk of NPEs, but you’ll likely need just as many checks to handle the empty value correctly as with null. Additionally, the semantics are different: An empty string represents a string with an empty value — null represents nothing. This becomes relevant if an application needs to distinguish between whether a user has not provided information vs. the user has entered some information in the form of the empty string value. You remove the risk of an NPE, but at the cost of using a somewhat misleading value.

有时使用的另一种替代方法是,当属性表示为简单字符串时,使用空字符串而不是null。 这消除了NPE的风险,但是您可能需要与使用null一样多的检查才能正确处理空值。 此外,语义也有所不同:空字符串表示具有空值的字符串-null表示什么。 如果应用程序需要区分用户是否提供信息与用户是否以空字符串值形式输入了一些信息,这将变得很重要。 您消除了NPE的风险,但以使用具有误导性的价值为代价。

Now let’s consider using null in the code that does not model real-life concepts. Most classes in an object-oriented code base have no counterpart in real life and only exist as an abstraction for infrastructure, processing and transformation and to group related functionality. Whether instantiations of these should be allowed to be represented with a null-value is less clear-cut. If we call a getter for a value with a very abstract type like TwoFactorComplexStrategyHandlerDelegateBean would we expect it to be null? Probably not. With a class that represents a concept from the real world, we can make an educated guess. But these types of classes leave us no chance. We can only know from reading the code. For that reason, returning null in place of these types should be avoided as people rarely have a reason to expect a null value. If you don’t expect null, why would you put in the effort to ensure your code is null-safe?

现在,让我们考虑在不对真实概念建模的代码中使用null。 面向对象的代码库中的大多数类在现实生活中没有对应对象,而仅作为基础结构,处理和转换以及与组相关的功能的抽象存在。 是否应该允许使用空值来表示这些实例的实例不太明确。 如果我们为具有非常抽象的类型(例如TwoFactorComplexStrategyHandlerDelegateBean)的值调用吸气剂,我们会期望它为null吗? 可能不是。 通过代表现实世界中概念的课程,我们可以做出有根据的猜测。 但是这些类型的课程让我们没有机会。 我们只能从阅读代码中知道。 因此,应避免返回null代替这些类型,因为人们很少有理由期望null值。 如果您不期望null,为什么还要努力确保代码是null安全的?

These objects that shouldn’t be represented by null are de facto. Not only in our own codebase but also in the JRE, libraries and frameworks. It’s problematic, but how problematic? It is important that even though we should try to minimize the usage of null, we shouldn’t trade having fewer null values for codebases full of complex workarounds to prevent values from becoming null. As I’ve discussed above, the alternatives are not always so great. There are, however, some cases of returning null that are easily avoidable, yet frequently seen. A returned null value for these classes often means that something is fishy. For instance, null is sometimes returned from getter-methods, where an object cannot be created due to some particular circumstance, like a server call in the method responding with an error. The method handles the error by logging in a catch-statement, and, instead of instantiating some object, returns null. Or when a method has certain preconditions for the parameters that are not met by the arguments, so again it just returns null. There’s an easy fix for these. An exception should be used to indicate that something is wrong and force the calling code into dealing with it. Returning null in these scenarios is misleading, does not ensure that the problem is handled and might forward the problem to some other part of the code, where it would have been better to fail fast.

这些不应该由null表示的对象实际上是 。 不仅在我们自己的代码库中,而且在JRE,库和框架中。 有问题,但是有问题吗? 重要的是,即使我们应该尝试最小化null的使用,我们也不应该为具有复杂变通办法的代码库使用较少的null值进行交易,以防止值变为null。 正如我上面所讨论的,替代方案并不总是那么好。 但是,有些返回空值的情况很容易避免,但很常见。 这些类返回的空值通常意味着有些东西是可疑的。 例如,有时会从getter方法返回null,在该方法中,由于某些特殊情况而无法创建对象,例如方法中响应错误的服务器调用。 该方法通过登录catch语句来处理错误,并且不实例化某些对象,而是返回null。 或者,当某个方法具有参数无法满足的某些特定前提条件时,那么它再次返回null。 有一个简单的解决方法。 应该使用异常来表明出了点问题,并迫使调用代码对其进行处理。 在这些情况下,返回null会产生误导,不能确保问题得到解决,并且可能会将问题转发到代码的其他部分,而在其他情况下最好还是快速失败 。

Another wrong usage of null is representing a has-a relation with a cardinality of 0..* (earlier I talked about 0..1 relations). Going back to our patient object, a patient may have one or more relatives registered. Or none. We would usually represent this with a list. However, I often see that people return null when there is no data to populate a list or other Collection types. Null is similarly used as an argument to methods in place of missing collections. Using null for this is bad for the following reasons. It is misleading, as the cardinality is perfectly representable with a collection. By assigning null to a Collection type, you only introduce unnecessary risk in your code. A for-loop based on a collection does nothing if the collection is empty, otherwise, it iterates over each element and does something. If you let a collection be null, you express the same thing as an empty list — no data to process here — however, you now need to ensure that there’s a null-check in every downstream method where you want to use the collection to avoid an NPE. Call methods with empty collections, when there is no data to provide. It’s as easy as calling Collections.emptyList(), emptyMap(), emptySet(), etc. Not a lot more work than declaring null, but a lot better.

空的另一种错误用法是表示具有-A为0的基数.. *(前面我谈到0..1关系)的关系。 回到我们的患者对象,患者可能已经注册了一个或多个亲戚。 还是没有。 我们通常用列表来表示。 但是,我经常看到,当没有数据可填充列表或其他Collection类型时,人们返回null。 类似地,将Null用作方法的参数来代替缺少的集合。 由于以下原因,为此使用null是不利的。 这是一种误导,因为基数完全可以用集合表示。 通过将null分配给Collection类型,只会在代码中引入不必要的风险。 如果集合为空,则基于集合的for循环不执行任何操作,否则,它将遍历每个元素并执行某些操作。 如果让集合为空,则表示与空列表相同的内容(此处没有要处理的数据),但是,现在您需要确保在每个要使用集合的下游方法中都进行空检查,以避免NPE。 当没有数据可提供时,调用具有空集合的方法。 就像调用Collections.emptyList(),emptyMap(),EmptySet()等一样简单。与声明null相比,它的工作并不多,但更好。

传递空参数 (Passing null-parameters)

It follows from the preceding section that it would be acceptable to use null arguments, when calling methods with domain-modelling parameter types with optional values, and the methods must ensure that it is safe to use these. In practice, null parameters are used for much more than that. Whenever we provide a null parameter to a method, we must ensure that all of the subsequent processing of the parameter is null-safe, which can be hard. Even though it appears so, your program might be in a state that hides unsafe behavior and only during other conditions does the problem become apparent. Providing null parameters also adds a risk of introducing errors, whenever we modify any code in the downstream flow from where it is provided.

从上一节可以得出,在调用带有可选值的域建模参数类型的方法时,使用空参数是可以接受的,并且这些方法必须确保安全使用它们。 实际上,空参数的用途远不止于此。 每当我们为方法提供空参数时,都必须确保对参数的所有后续处理都是空安全的,这可能很困难。 即使看起来像这样,您的程序也可能处于隐藏不安全行为的状态,并且仅在其他情况下问题才变得明显。 每当我们从提供它的地方在下游流中修改任何代码时,提供空参数还增加了引入错误的风险。

What can be done to avoid null parameters in general?

一般如何避免空参数?

Often we need to use some functionality in an existing method, but the calling context that we’re in is slightly different, and we can’t provide all the values the method calls for, or we need to provide more information than the method was initially designed for. We obviously don’t want to reimplement a virtually identical method. Code reuse is one of the pillars of maintainable code; the same functionality should not be implemented in multiple places as it introduces extra work to keep the code in sync and risk of errors. So, we modify the existing code for our purposes and use null for parameters that aren’t always provided. Some methods can by design tolerate at least some null-parameters, while others can’t. However, it can be hard to figure out which parameters are allowed to be null, and if null is even the correct value for a missing value.

通常,我们需要在现有方法中使用某些功能,但是我们所处的调用上下文略有不同,并且我们无法提供该方法调用的所有值,或者我们需要提供比该方法更多的信息。最初设计用于。 我们显然不想重新实现几乎相同的方法。 代码重用是可维护代码的Struts之一。 不应在多个地方实现相同的功能,因为它会引入额外的工作来保持代码同步和错误风险。 因此,出于我们的目的,我们修改了现有代码,并对并非总是提供的参数使用null。 通过设计,某些方法可以至少容忍某些空参数,而其他方法则不能。 但是,很难弄清楚哪些参数允许为空,如果空值甚至是缺失值的正确值,则很难确定。

In a language like Python, method signatures may contain default values for parameters that are used if an argument value is left out of a method call. However, this is not possible in Java. The closest thing is to use method overloading, where the same method signature is defined multiple times in a class with different parameters. One method will contain the full functionality and take the full set of parameters, while the others are just “decorators” for calling the method that each takes some subset of the parameters. The decorator methods define what values should be used in place in the missing parameters, so the caller won’t have to provide these. By hard-coding, which values should be provided when the caller doesn’t have all the values, we reduce the risk of errors and make the acceptable parameter values explicit.

在Python之类的语言中,方法签名可能包含参数的默认值,如果在方法调用中忽略了参数值,则使用这些参数的默认值。 但是,这在Java中是不可能的。 最接近的方法是使用方法重载 ,即在具有不同参数的类中多次定义相同的方法签名。 一种方法将包含全部功能并采用完整的参数集,而其他方法只是用于调用该方法的“装饰器”,而每种方法都采用某些参数子集。 装饰器方法定义在丢失的参数中应使用哪些值,因此调用方将不必提供这些值。 通过硬编码,当调用者没有所有值时应提供哪些值,我们降低了出错的风险,并明确了可接受的参数值。

You can similarly decompose constructors, but you could also use the Builder design pattern. The Builder design pattern helps to minimize constructor parameters and removes the need for passing null-values to the constructor by using a Builder object for creating your class. The gist of the pattern is that you instantiate an object indirectly through an intermediary builder class. To provide the arguments that you would have passed to the constructor directly, you call a setter corresponding to each. If a value has not been set by you, the builder will provide it instead. You then call Create() on the builder, and it instantiates the object for you. It’s a bit too complex to go into detail with here, but Refactoring.guru has a very nice article on the pattern and the trade-offs of using it. As with most patterns, it introduces extra classes and complexity, so before using it, make sure that it makes sense; using it just to avoid calling a constructor with a few null values is probably a bit overkill.

您可以类似地分解构造函数,但也可以使用Builder设计模式 。 Builder设计模式有助于最小化构造函数参数,并通过使用Builder对象来创建类而无需将null值传递给构造函数。 模式的要旨是您通过中间构建器类间接实例化对象。 要提供直接传递给构造函数的参数,请调用与每个参数对应的setter。 如果您尚未设置值,那么构建器将改为提供它。 然后,您在构建器上调用Create(),它将为您实例化该对象。 这里有点复杂,但是Refactoring.guru上有一篇很好的文章介绍了模式和使用它的权衡。 与大多数模式一样,它引入了额外的类和复杂性,因此在使用它之前,请确保它有意义。 仅使用它以避免调用带有几个null值的构造函数可能有点过头。

In the solutions above, null-values are still being passed to methods internally in the object, but caller and called methods are intended to do so by design. Any method called with one of these values is expected to have proper null-handling in place. Outside callers should be prevented from providing null-values for parameters that were not considered in the design, as null-values might not be supported and proper handling is not be guaranteed.

在上面的解决方案中,空值仍在内部传递给对象中的方法,但是调用者和被调用方法是设计使然的。 使用这些值之一调用的任何方法都应具有适当的空值处理。 应避免外部调用者为设计中未考虑的参数提供空值,因为可能不支持空值并且不能保证正确的处理。

如何思考null (How to think about null)

An increasing number of programming languages are starting to use a “safety on” approach to certain features. In languages like Clojure, F# and Rust variables are immutable by default; the compiler will only allow variables that are declared with a special modifier to change value. This approach to dangerous features forces programmers to override the default behavior, thereby indicating “I understand this is dangerous, I know what I’m doing and have a good reason for doing so”; doing so should not be the norm. We should think about null in the same way. We need to reserve the value for a few special cases, where it is the right thing to use, but generally, we should restrict ourselves to not use it — however, not at the cost of introducing complexity with creative workarounds. Whenever considering using null in place of a value that crosses the boundary between methods, you should take a moment to consider if you have a good reason for doing so, if you can guarantee it doesn’t end up somewhere it can cause trouble and if other developers would expect the value to be null. If not, you should reconsider the alternatives.

越来越多的编程语言开始对某些功能使用“安全开启”方法。 在Clojure之类的语言中,默认情况下F#和Rust变量是不可变的。 编译器将只允许使用特殊修饰符声明的变量来更改值。 这种危险功能的方法迫使程序员重写默认行为,从而表明“我知道这很危险,我知道自己在做什么,并且有充分的理由这样做”; 这样做不应该是常态。 我们应该以同样的方式考虑null。 我们需要为一些特殊情况保留价值,在某些特殊情况下,使用它是正确的事情,但是通常,我们应该限制自己不要使用它-但是,这不以通过创造性的变通办法引入复杂性为代价。 每当考虑使用null代替跨越方法之间边界的值时,您都应该花一点时间考虑一下是否有这样做的充分理由,如果可以保证它不会终止于某处会引起麻烦,以及其他开发人员希望该值为null。 如果不是,则应重新考虑替代方案。

Curious to know more?… “Part 2: There’s got to be a better way — modern null handling” is going live Friday 21st August on the Destination AARhus TechBlog.

是否想知道更多?……“第2部分:必有更好的方法-现代的null处理”将于8月21日(星期五)在Destination AARhus TechBlog上线。

By Jens Christian B. MadsenSystems Developer, Systematic

作者:Jens Christian B. Madsen系统开发人员

About meJens Christian B. Madsen is a developer on the Columna clinical information system, holds master’s degrees from Aarhus University in Molecular biology and Computer Science and is a certified ethical hacker. He has contributed to books on such topics as python, computer science and Linux. He enjoys heavy books, heavy metal and heavy weights.

关于我 Jens Christian B. Madsen是Columna临床信息系统的开发人员,拥有奥尔胡斯大学分子生物学和计算机科学专业的硕士学位,并且是一名经过认证的道德黑客。 他为诸如python,计算机科学和Linux等主题的书籍做出了贡献。 他喜欢沉重的书籍,沉重的金属和沉重的重物。

翻译自: /destinationaarhus-techblog/avoiding-null-pointer-exceptions-in-a-modern-java-application-5e54fab6e3b

java避免空指针异常

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。