当前位置:网站首页>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
边栏推荐
- Pytorch——数据加载和处理
- PyEMD安装及简单使用
- Shansi Valley P290 polymorphism exercise
- 2. Devops sonar installation
- Multithreading and high concurrency (2) -- detailed explanation of synchronized usage
- Complete example demonstration of creating table to page - joint table query
- Pytorch notes - complete code for linear regression & manual or automatic calculation of gradient code comparison
- Pytorch学习记录(七):处理数据和训练模型的技巧
- Anaconda安装PyQt5 和 pyqt5-tools后没有出现designer.exe的问题解决
- 对比学习论文——[MoCo,CVPR2020]Momentum Contrast for Unsupervised Visual Representation Learning
猜你喜欢
去噪论文阅读——[RIDNet, ICCV19]Real Image Denoising with Feature Attention
Pytorch learning record (XII): learning rate attenuation + regularization
去噪论文阅读——[CVPR2022]Blind2Unblind: Self-Supervised Image Denoising with Visible Blind Spots
开发环境 EAS登录 license 许可修改
Latex quick start
无监督去噪——[TMI2022]ISCL: Interdependent Self-Cooperative Learning for Unpaired Image Denoising
Pyemd installation and simple use
线性代数第二章-矩阵及其运算
PyQy5学习(二):QMainWindow+QWidget+QLabel
lambda expressions
随机推荐
Automatic control (Han min version)
Pytorch學習記錄(十三):循環神經網絡((Recurrent Neural Network)
SQL injection
Framework analysis 2 Source code - login authentication
Anaconda
Multithreading and high concurrency (2) -- detailed explanation of synchronized usage
Filebrowser realizes private network disk
Paper on Image Restoration - [red net, nips16] image restoration using very deep revolutionary encoder decoder networks wi
Solution record of slow access speed of SMB service in redhat6
The bottom implementation principle of thread - static agent mode
Conda 虚拟环境管理(创建、删除、克隆、重命名、导出和导入)
Pytorch学习记录(十):数据预处理+Batch Normalization批处理(BN)
umi官网yarn create @umijs/umi-app 报错:文件名、目录名或卷标语法不正确
Understand the current commonly used encryption technology system (symmetric, asymmetric, information abstract, digital signature, digital certificate, public key system)
Write your own redistemplate
DBCP usage
Pytorch learning record (IV): parameter initialization
PyTorch入门小笔记——利用简单例子观察前向传播各个层输出的size
Reading of denoising paper - [ridnet, iccv19] real image denoising with feature attention
Pyqy5 learning (2): qmainwindow + QWidget + qlabel