当前位置:网站首页>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:]所创,转载请带上原文链接,感谢
边栏推荐
- 擅长To C的腾讯,如何借腾讯云在这几个行业云市场占有率第一?
- 分布式文档存储数据库之MongoDB基础入门
- Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
- Adobe Lightroom / LR 2021 software installation package (with installation tutorial)
- 用 Python 写出来的进度条,竟如此美妙~
- 11 server monitoring tools commonly used by operation and maintenance personnel
- 值得一看!EMR弹性低成本离线大数据分析最佳实践(附网盘链接)
- 还不快看!对于阿里云云原生数据湖体系全解读!(附网盘链接)
- 为什么 Schnorr 签名被誉为比特币 Segwit 后的最大技术更新
- If you don't understand the gap with others, you will never become an architect! What's the difference between a monthly salary of 15K and a monthly salary of 65K?
猜你喜欢

Major changes in Huawei's cloud: Cloud & AI rises to Huawei's fourth largest BG with full fire

Implementation of verification code recognition in Python opencv pytesseract

YGC问题排查,又让我涨姿势了!

年轻一代 winner 的程序人生,改变世界的起点藏在身边

python基础教程python opencv pytesseract 验证码识别的实现

On monotonous stack
![[data structure Python description] use hash table to manually implement a dictionary class based on Python interpreter](/img/3b/00bc81122d330c9d59909994e61027.jpg)
[data structure Python description] use hash table to manually implement a dictionary class based on Python interpreter

Flink的sink实战之一:初探

一文剖析2020年最火十大物联网应用|IoT Analytics 年度重磅报告出炉!

笔试面试题目:判断单链表是否有环
随机推荐
最全!阿里巴巴经济体云原生实践!(附网盘链接)
Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
Windows10关机问题----只有“睡眠”、“更新并重启”、“更新并关机”,但是又不想更新,解决办法
为 Docsify 自动生成 RSS 订阅
Learning summary (about deep learning, vision and learning experience)
Hematemesis! Alibaba Android Development Manual! (Internet disk link attached)
python基础教程python opencv pytesseract 验证码识别的实现
It's 20% faster than python. Are you excited?
Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
华为云重大变革:Cloud&AI 升至华为第四大 BG ,火力全开
BCCOIN告诉您:年底最靠谱的投资项目是什么!
Python basic syntax
如何将 PyTorch Lightning 模型部署到生产中
Ali teaches you how to use the Internet of things platform! (Internet disk link attached)
维图PDMS切图软件
Entry level! Teach you how to develop small programs without asking for help (with internet disk link)
We interviewed the product manager of SQL server of Alibaba cloud database, and he said that it is enough to understand these four problems
Close to the double 11, he made up for two months and successfully took the offer from a large factory and transferred to Alibaba
一文剖析2020年最火十大物联网应用|IoT Analytics 年度重磅报告出炉!
Bohai bank million level fines continue: Li Volta said that the governance is perfect, the growth rate is declining