异常 - 如何更好地处理 java NullPointerException (一整套完整心法) ?
伊谢尔伦
伊谢尔伦 2017-04-18 10:34:35
0
2
419

2017/1/8

描述

可以说是「优雅地」处理, 总的来说要逻辑严谨, 即讲清楚 why

自己脑海有某些原则, 但是总不是不系统, 这令我不安.

上下文环境

  1. Java 8

伊谢尔伦
伊谢尔伦

小伙看你根骨奇佳,潜力无限,来学PHP伐。

reply all(2)
刘奇

Just to mention a few that are more commonly used or more official:

java8 provides the optional class for null pointer checking,
Guava provides Preconditions.checkNotNull for checking,
lombok provides the NonNull annotation

However, in actual use, if(map!=null&&map.get("a")!=null) is relatively simple and intuitive, and lombok is very elegant to use.
As for the handling methods of java8 and guava, it is a matter of opinion.

Ty80

The meaning of optional is to tell you through the type system that you should perform null checking, but you don’t need to check for variables that are not optional? No, you still have to check. Therefore, the use of optional is awkward, and unless it is new code, it is difficult to handle it consistently.

optional refers to option/maybe in functional languages, but there is usually no null in functional languages. If you see an option, you will detect it. If there is no option, you don’t need to check. The processing is consistent.

Recent TypeScript supports strictNullCheck and union type. Null becomes a separate type. Combined with union type, it can represent nullable types at the type level (such as string | null). strictNullCheck requires that all nullable variables must be checked before use.

You can annotate and mark NonNull in Java, and then use tools to detect it, and the effect is almost the same.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!