当前位置:网站首页>Optional best practices
Optional best practices
2022-04-23 06:08:00 【New ape and horse】
Catalog
3、 ... and Optional Best practices
3.1 Don't go straight back null, Use Optional.empty();
3.2 Use... Correctly ifPresent()
3.3 To use less get(), multi-purpose orElse() and orElseGet()
3.4 To use less of(), multi-purpose ofNullable()
One Optional What is it?
Optional The author of Brian Goetz For this API Explanation :
Our intention was to provide a limited mechanism for library method return types where there needed to be a clear way to represent "no result", and using null for such was overwhelmingly likely to cause errors.
for fear of null The mistake , We provide a finite mechanism for explicitly representing null values .
Optional It's a container , Used to place values that may be empty , It can be handled reasonably and gracefully null.
Two Optional API Introduce
public static<T> Optional<T> empty(); // Return to one Optional Container object
public static <T> Optional<T> of(T value); // Create a Optional object , If value yes null, Throw out NPE
public static <T> Optional<T> ofNullable(T value); // Create a Optional object , but value Return for space time Optional.empty()
public T get(); // return Optional The value of the middle package , Before sentencing , Never use directly
public boolean isPresent(); // Judge Optional Is there any value in , return boolean
public void ifPresent(Consumer<? super T> consumer); // Judge Optional Is there any value in , If there is a value, execute consumer, Or nothing
public T orElse(T other); // return Optional The value of the middle package , But the difference is that when you can't get a value , Return your specified default
public T orElseGet(Supplier<? extends T> other); // return Optional The value of the middle package , When the value cannot be obtained , Return your specified default
public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier); // return Optional The value of the middle package , Throw the specified exception when the value cannot be obtained
3、 ... and Optional Best practices
Optional It belongs to the return type , It is usually used in business return value or remote call .
3.1 Don't go straight back null, Use Optional.empty();
// Use Optional.empty() Before
private PoiTabHintDTO getPoiTabHintFromTask(FutureTask<PoiTabHintDTO> task) {
if (Objects.isNull(task)) {
return null;
}
try {
return ThreadPoolUtils.get(task, 4, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("getRdcPoiTabHintFromTask", e);
Cat.logMetricForCount("getRdcPoiTabHintFromTask");
return null;
}
}
// Use Optional.empty()
private Optional<PoiTabHintDTO> getPoiTabHintFromTask(FutureTask<Optional<PoiTabHintDTO>> task) {
if (Objects.isNull(task)) {
return Optional.empty();
}
try {
return ThreadPoolUtils.get(task, 4, TimeUnit.SECONDS);
} catch (Exception e) {
log.error("getRdcPoiTabHintFromTask", e);
Cat.logMetricForCount("getRdcPoiTabHintFromTask");
return Optional.empty();
}
}
// What needs to be displayed is from optional Get objects from the container , Can reduce NPE The birth of .
3.2 Use... Correctly ifPresent()
// Use ifPresent() Before
if (getPoiTabHintFromTask(rdcPoiHintTask).isPresent()) {
poiTabHintList.add(getPoiTabHintFromTask(rdcPoiHintTask).get());
}
// Use ifPresent()
getPoiTabHintFromTask(rdcPoiHintTask).ifPresent(poiTabHintList::add);
// There's no performance improvement , Code becomes simple .
3.3 To use less get(), multi-purpose orElse() and orElseGet()
// orElse() Applicable to input parameters are specific values
public static ConfirmAuthorizationEnum getByCode(int code) {
return Arrays.stream(ConfirmAuthorizationEnum.values())
.filter(x -> code == x.getCode())
.findFirst()
.orElse(ConfirmAuthorizationEnum.UNINITIALIZED);
}
// orElseGet() Apply to lamda expression
private Optional<DeliveryReturnBillBO> getReturnBillFromList(
List<DeliveryReturnBillBO> allDeliveryReturnBillList, String returnBillNo) {
return Optional.ofNullable(allDeliveryReturnBillList.stream()
.filter(deliveryReturnBillBO -> returnBillNo.equals(deliveryReturnBillBO.getReturnBillNo()))
.findFirst()
.orElseGet(() -> {
log.error(" No refund order was obtained {} Details of ", returnBillNo);
Cat.logMetricForCount(DeliveryBill.RELATED_RETURN_BILL_IS_NULL);
return null;
}));
}
// Why use less get(), It needs to be used in combination with air judgment , This sum !=null It doesn't make much difference .
3.3 To use less get(), multi-purpose orElse() and orElseGet()
// orElse() Applicable to input parameters are specific values
public static ConfirmAuthorizationEnum getByCode(int code) {
return Arrays.stream(ConfirmAuthorizationEnum.values())
.filter(x -> code == x.getCode())
.findFirst()
.orElse(ConfirmAuthorizationEnum.UNINITIALIZED);
}
// orElseGet() Apply to lamda expression
private Optional<DeliveryReturnBillBO> getReturnBillFromList(
List<DeliveryReturnBillBO> allDeliveryReturnBillList, String returnBillNo) {
return Optional.ofNullable(allDeliveryReturnBillList.stream()
.filter(deliveryReturnBillBO -> returnBillNo.equals(deliveryReturnBillBO.getReturnBillNo()))
.findFirst()
.orElseGet(() -> {
log.error(" No refund order was obtained {} Details of ", returnBillNo);
Cat.logMetricForCount(DeliveryBill.RELATED_RETURN_BILL_IS_NULL);
return null;
}));
}
// Why use less get(), It needs to be used in combination with air judgment , This sum !=null It doesn't make much difference .
3.4 To use less of(), multi-purpose ofNullable()
// Use of() scene
if (Objects.isNull(returnBillProcessBo)) {
return Optional.empty();
}
return Optional.of(returnBillProcessBo);
// Use ofNullable() scene
return Optional.ofNullable(returnBillProcessBo);
版权声明
本文为[New ape and horse]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204220533487544.html
边栏推荐
- 去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots
- 编写一个自己的 RedisTemplate
- JDBC connection database
- 图像恢复论文简记——Uformer: A General U-Shaped Transformer for Image Restoration
- Filebrowser realizes private network disk
- 你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问
- PyTorch笔记——观察DataLoader&用torch构建LeNet处理CIFAR-10完整代码
- 线性代数第二章-矩阵及其运算
- Pytorch learning record (IX): convolutional neural network in pytorch
- PyTorch笔记——通过搭建ResNet熟悉网络搭建方式(完整代码)
猜你喜欢

Chapter 4 of line generation - linear correlation of vector systems

给yarn配置国内镜像加速器

深度学习基础——简单了解meta learning(来自李宏毅课程笔记)

Fundamentals of digital image processing (Gonzalez) I
![对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning](/img/21/4bc94fe29f416c936436c04fc16fa8.png)
对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning

String notes

PyTorch笔记——实现线性回归完整代码&手动或自动计算梯度代码对比

Pyqy5 learning (III): qlineedit + qtextedit

Multithreading and high concurrency (3) -- synchronized principle

Pytorch学习记录(三):神经网络的结构+使用Sequential、Module定义模型
随机推荐
Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
数字图像处理基础(冈萨雷斯)二:灰度变换与空间滤波
Shansi Valley P290 polymorphism exercise
Multithreading and high concurrency (2) -- detailed explanation of synchronized usage
PyTorch笔记——观察DataLoader&用torch构建LeNet处理CIFAR-10完整代码
线性代数第三章-矩阵的初等变换与线性方程组
你不能访问此共享文件夹,因为你组织的安全策略阻止未经身份验证的来宾访问
对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning
Pytorch学习记录(十三):循环神经网络((Recurrent Neural Network)
Traitement des séquelles du flux de Tensor - exemple simple d'enregistrement de torche. Utils. Données. Dataset. Problème de dimension de l'image lors de la réécriture de l'ensemble de données
JSP syntax and JSTL tag
Latex quick start
Fundamentals of digital image processing (Gonzalez) I
Development environment EAS login license modification
Pytorch學習記錄(十三):循環神經網絡((Recurrent Neural Network)
Pytorch学习记录(七):处理数据和训练模型的技巧
Numpy common function table sorting of data processing
Conda 虚拟环境管理(创建、删除、克隆、重命名、导出和导入)
线代第四章-向量组的线性相关
去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots