当前位置:网站首页>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
边栏推荐
- Get the value of state in effects in DVA
- Linear algebra Chapter 2 - matrices and their operations
- Kingdee EAS "general ledger" system calls "de posting" button
- You cannot access this shared folder because your organization's security policy prevents unauthenticated guests from accessing it
- How to use comparative learning to do unsupervised - [cvpr22] training & [eccv20] image translation
- How to grow at work
- Fundamentals of in-depth learning -- a simple understanding of meta learning (from Li Hongyi's course notes)
- PyQy5学习(四):QAbstractButton+QRadioButton+QCheckBox
- The official website of UMI yarn create @ umijs / UMI app reports an error: the syntax of file name, directory name or volume label is incorrect
- The problem that the page will refresh automatically after clicking the submit button on the form is solved
猜你喜欢

线代第四章-向量组的线性相关

PyQy5学习(二):QMainWindow+QWidget+QLabel

Pytorch learning record (XII): learning rate attenuation + regularization

卡尔曼滤波与惯性组合导航

Font shape `OMX/cmex/m/n‘ in size <10.53937> not available (Font) size <10.95> substituted.

Pytoch -- data loading and processing
![Reading of denoising paper - [ridnet, iccv19] real image denoising with feature attention](/img/4e/1a51636853d11544e6f5c37a588730.png)
Reading of denoising paper - [ridnet, iccv19] real image denoising with feature attention

JDBC connection database

Dva中在effects中获取state的值

Paper on LDCT image reconstruction: edge enhancement based transformer for medical image denoising
随机推荐
lambda expressions
Complete example demonstration of creating table to page - joint table query
Pytorch学习记录(十三):循环神经网络((Recurrent Neural Network)
Solution record of slow access speed of SMB service in redhat6
String notes
C3p0 database connection pool usage
JVM family (4) -- memory overflow (OOM)
Three ways to create threads
umi官网yarn create @umijs/umi-app 报错:文件名、目录名或卷标语法不正确
In depth source code analysis servlet first program
Understand the current commonly used encryption technology system (symmetric, asymmetric, information abstract, digital signature, digital certificate, public key system)
PyQy5学习(二):QMainWindow+QWidget+QLabel
EditorConfig
What is the difference between the basic feasible solution and the basic feasible solution in linear programming?
IO multiplexing of 09 redis
MySQL basic madness theory
对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning
在Jupyter notebook中用matplotlib.pyplot出现服务器挂掉、崩溃的问题
Multithreading and high concurrency (1) -- basic knowledge of threads (implementation, common methods, state)
PyTorch笔记——通过搭建ResNet熟悉网络搭建方式(完整代码)