当前位置:网站首页>Eight ways to optimize if else code
Eight ways to optimize if else code
2020-11-08 12:11:00 【See also:】
Preface
Code if if-else More , It's difficult to read , It's also difficult to maintain , It's easy to get out of bug, Next , This article will introduce optimization if-else Eight schemes of code .
Optimization plan 1 : advance return, Remove unnecessary else
If if-else The code block contains return sentence , Think ahead of time return, Put the superfluous else kill , Make the code more elegant .
Before optimization :
if
(
condition
){
//doSomething
}
else
{
return
;
}
After optimization :
if
(!
condition
){
return
;
}
//doSomething
Optimization scheme II : Use conditional binomial operators
Using conditional trinomial operators can simplify some if-else, Make the code more concise , More readable .
Before optimization :
int
price
;
if
(
condition
){
price
=
80
;
}
else
{
price
=
100
;
}
After optimization :
int
price
=
condition
?
80
:
100
;
Optimization plan 3 : Use enumeration
At some point , Enumerations can also be used to optimize if-else The branch of logic , On a personal level , It can also be seen as a table driven approach .
Before optimization :
String
OrderStatusDes
;
if
(
orderStatus
==
0
){
OrderStatusDes
=
" Order not paid "
;
}
else
if
(
OrderStatus
==
1
){
OrderStatusDes
=
" The order has been paid "
;
}
else
if
(
OrderStatus
==
2
){
OrderStatusDes
=
" Shipped "
;
}
...
After optimization :
Define an enumeration first
:
public
enum
OrderStatusEnum
{
UN_PAID
(
0
,
" Order not paid "
),
PAIDED
(
1
,
" The order has been paid "
),
SENDED
(
2
,
" Shipped "
),;
private
int
index
;
private
String
desc
;
public
int
getIndex
()
{
return
index
;
}
public
String
getDesc
()
{
return
desc
;
}
OrderStatusEnum
(
int
index
,
String
desc
){
this
.
index
=
index
;
this
.
desc
=
desc
;
}
OrderStatusEnum
of
(
int
orderStatus
)
{
for
(
OrderStatusEnum
temp
:
OrderStatusEnum
.
values
())
{
if
(
temp
.
getIndex
()
==
orderStatus
)
{
return
temp
;
}
}
return
null
;
}
}
With enumeration , above if-else The branch of logic , Can be optimized to a line of code
String
OrderStatusDes
=
OrderStatusEnum
.
0f
(
orderStatus
).
getDesc
();
Optimization plan 4 : Merge conditional expressions
If there are a series of conditions that return the same result , You can combine them into a conditional expression , Make the logic clearer .
Before optimization
double
getVipDiscount
()
{
if
(
age
<
18
){
return
0.8
;
}
if
(
" Shenzhen "
.
equals
(
city
)){
return
0.8
;
}
if
(
isStudent
){
return
0.8
;
}
//do somethig
}
After optimization
double
getVipDiscount
(){
if
(
age
<
18
||
" Shenzhen "
.
equals
(
city
)||
isStudent
){
return
0.8
;
}
//doSomthing
}
Optimization plan 5 : Use Optional
occasionally if-else More , It's because of non empty judgment , You can use java8 Of Optional To optimize .
Before optimization :
String
str
=
"jay@huaxiao"
;
if
(
str
!=
null
)
{
System
.
out
.
println
(
str
);
}
else
{
System
.
out
.
println
(
"Null"
);
}
After optimization :
Optional
<
String
>
strOptional
=
Optional
.
of
(
"jay@huaxiao"
);
strOptional
.
ifPresentOrElse
(
System
.
out
::
println
,
()
->
System
.
out
.
println
(
"Null"
));
Optimization plan 6 : Table driven method
Table driven method , Also known as table driven 、 Table drive method . The table driven method is a way for you to find information in a table , Instead of using a lot of logic (if or case) The way to find them . Following demo, hold map Abstract into a table , stay map Search for information , Instead of unnecessary logical statements .
Before optimization :
if
(
param
.
equals
(
value1
))
{
doAction1
(
someParams
);
}
else
if
(
param
.
equals
(
value2
))
{
doAction2
(
someParams
);
}
else
if
(
param
.
equals
(
value3
))
{
doAction3
(
someParams
);
}
// ...
After optimization :
Map
<?,
Function
<?>
action
>
actionMappings
=
new
HashMap
<>();
// Here's the generics ? For the convenience of demonstration , It can be replaced by the type you need
// initialization
actionMappings
.
put
(
value1
,
(
someParams
)
->
{
doAction1
(
someParams
)});
actionMappings
.
put
(
value2
,
(
someParams
)
->
{
doAction2
(
someParams
)});
actionMappings
.
put
(
value3
,
(
someParams
)
->
{
doAction3
(
someParams
)});
// Omit redundant logical statements
actionMappings
.
get
(
param
).
apply
(
someParams
);
Optimization plan 7 : Optimize the logical structure , Let the normal process take the main line
Before optimization :
public
double
getAdjustedCapital
(){
if
(
_capital
<=
0.0
){
return
0.0
;
}
if
(
_intRate
>
0
&&
_duration
>
0
){
return
(
_income
/
_duration
)
*
ADJ_FACTOR
;
}
return
0.0
;
}
After optimization :
public
double
getAdjustedCapital
(){
if
(
_capital
<=
0.0
){
return
0.0
;
}
if
(
_intRate
<=
0
||
_duration
<=
0
){
return
0.0
;
}
return
(
_income
/
_duration
)
*
ADJ_FACTOR
;
}
Reverse the condition so that the exception exits first , Keep the normal process in the main process , Can make the code structure clearer .
Optimization plan 8 : The strategy pattern + Factory methods eliminate if else
Suppose the demand is , Depending on the type of medal , Deal with the corresponding medal service , Before optimization, there is the following code :
String
medalType
=
"guest"
;
if
(
"guest"
.
equals
(
medalType
))
{
System
.
out
.
println
(
" Medal of honor "
);
}
else
if
(
"vip"
.
equals
(
medalType
))
{
System
.
out
.
println
(
" The medal of Membership "
);
}
else
if
(
"guard"
.
equals
(
medalType
))
{
System
.
out
.
println
(
" Show the guardian medal "
);
}
...
First , We put each conditional logic block , Abstract into a public interface , You can get the following code :
// Medal interface
public
interface
IMedalService
{
void
showMedal
();
String
getMedalType
();
}
According to every logical condition , Define the corresponding policy implementation class , You can get the following code :
// Guardian medal strategy implementation class
public
class
GuardMedalServiceImpl
implements
IMedalService
{
@Override
public
void
showMedal
()
{
System
.
out
.
println
(
" Show the guardian medal "
);
}
@Override
public
String
getMedalType
()
{
return
"guard"
;
}
}
// Guest medal strategy implementation class
public
class
GuestMedalServiceImpl
implements
IMedalService
{
@Override
public
void
showMedal
()
{
System
.
out
.
println
(
" Medal of honor "
);
}
@Override
public
String
getMedalType
()
{
return
"guest"
;
}
}
//VIP Medal strategy implementation class
public
class
VipMedalServiceImpl
implements
IMedalService
{
@Override
public
void
showMedal
()
{
System
.
out
.
println
(
" The medal of Membership "
);
}
@Override
public
String
getMedalType
()
{
return
"vip"
;
}
}
Next , Let's define the policy factory class , To manage these medal implementation strategy classes , as follows :
// Medal service industry
public
class
MedalServicesFactory
{
private
static
final
Map
<
String
,
IMedalService
>
map
=
new
HashMap
<>();
static
{
map
.
put
(
"guard"
,
new
GuardMedalServiceImpl
());
map
.
put
(
"vip"
,
new
VipMedalServiceImpl
());
map
.
put
(
"guest"
,
new
GuestMedalServiceImpl
());
}
public
static
IMedalService
getMedalService
(
String
medalType
)
{
return
map
.
get
(
medalType
);
}
}
Used strategy + After factory mode , The code is much simpler , as follows :
public
class
Test
{
public
static
void
main
(
String
[]
args
)
{
String
medalType
=
"guest"
;
IMedalService
medalService
=
MedalServicesFactory
.
getMedalService
(
medalType
);
medalService
.
showMedal
();
}
}
Reference and thanks
- 6 An example explains how to if-else Code recombines high quality code
-
how “ kill ” if...else
Official account number
- If you think it's well written, please give me a compliment + Pay attention to , thank you ~
- At the same time, I am very much expecting my buddies to pay attention to my official account , Later, better dry goods will be introduced slowly ~ Hee hee
版权声明
本文为[See also:]所创,转载请带上原文链接,感谢
边栏推荐
- 用 Python 写出来的进度条,竟如此美妙~
- Why is Schnorr Signature known as the biggest technology update after bitcoin segwit
- This time Kwai tiktok is faster than shaking.
- 啥是数据库范式
- Analysis of istio access control
- IQKeyboardManager 源代码看看
- Ali tear off the e-commerce label
- Introduction to mongodb foundation of distributed document storage database
- 一文读懂机器学习“数据中毒”
- Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
猜你喜欢
Implementation of verification code recognition in Python opencv pytesseract
原创 | 数据资产确权浅议
Xamarin 从零开始部署 iOS 上的 Walterlv.CloudKeyboard 应用
The young generation of winner's programming life, the starting point of changing the world is hidden around
渤海银行百万级罚单不断:李伏安却称治理完善,增速呈下滑趋势
Rust: performance test criteria Library
Flink从入门到真香(6、Flink实现UDF函数-实现更细粒度的控制流)
The most complete! Alibaba economy cloud original practice! (Internet disk link attached)
Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
It's 20% faster than python. Are you excited?
随机推荐
This paper analyzes the top ten Internet of things applications in 2020!
What can your cloud server do? What is the purpose of cloud server?
浅谈单调栈
We interviewed the product manager of SQL server of Alibaba cloud database, and he said that it is enough to understand these four problems
Istio traffic management -- progress gateway
On the confirmation of original data assets
Rust: performance test criteria Library
运维人员常用到的 11 款服务器监控工具
应届生年薪35w+ !倒挂老员工,互联网大厂薪资为何越来越高?
Flink从入门到真香(10、Sink数据输出-Elasticsearch)
next.js实现服务端缓存
Rust : 性能测试criterion库
Or talk No.19 | Facebook Dr. Tian Yuandong: black box optimization of hidden action set based on Monte Carlo tree search
[data structure Python description] use hash table to manually implement a dictionary class based on Python interpreter
Why is Schnorr Signature known as the biggest technology update after bitcoin segwit
IQKeyboardManager 源代码看看
原创 | 数据资产确权浅议
Improvement of rate limit for laravel8 update
The young generation of winner's programming life, the starting point of changing the world is hidden around
擅长To C的腾讯,如何借腾讯云在这几个行业云市场占有率第一?