当前位置:网站首页>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:]所创,转载请带上原文链接,感谢
边栏推荐
- How to write a resume and project
- How to deploy pytorch lightning model to production
- 后端程序员必备:分布式事务基础篇
- Ali tear off the e-commerce label
- C语言I博客作业03
- Q & A and book giving activities of harbor project experts
- When kubernetes encounters confidential computing, see how Alibaba protects the data in the container! (Internet disk link attached)
- It's worth seeing! EMR elastic low cost offline big data analysis best practice (with network disk link)
- 不多不少,大学里必做的五件事(从我的大一说起)
- TiDB 性能竞赛 11.02-11.06
猜你喜欢
Analysis of ArrayList source code
The container with the most water
A scheme to improve the memory utilization of flutter
笔试面试题目:盛水最多的容器
Introduction to mongodb foundation of distributed document storage database
不多不少,大学里必做的五件事(从我的大一说起)
个人目前技术栈
新的目标市场在哪里?锚定的产品是什么?| 十问2021中国企业服务
Close to the double 11, he made up for two months and successfully took the offer from a large factory and transferred to Alibaba
Windows10关机问题----只有“睡眠”、“更新并重启”、“更新并关机”,但是又不想更新,解决办法
随机推荐
IQKeyboardManager 源代码看看
Why is Schnorr Signature known as the biggest technology update after bitcoin segwit
2018中国云厂商TOP5:阿里云、腾讯云、AWS、电信、联通 ...
It's worth seeing! EMR elastic low cost offline big data analysis best practice (with network disk link)
Win10 Terminal + WSL 2 安装配置指南,精致开发体验
Entry level! Teach you how to develop small programs without asking for help (with internet disk link)
Adobe Lightroom / LR 2021 software installation package (with installation tutorial)
Hematemesis! Alibaba Android Development Manual! (Internet disk link attached)
Windows10关机问题----只有“睡眠”、“更新并重启”、“更新并关机”,但是又不想更新,解决办法
How to write a resume and project
Written interview questions: find the smallest positive integer missing
Iqkeyboardmanager source code to see
C语言I博客作业03
Ali teaches you how to use the Internet of things platform! (Internet disk link attached)
Top 5 Chinese cloud manufacturers in 2018: Alibaba cloud, Tencent cloud, AWS, telecom, Unicom
Win10 terminal + WSL 2 installation and configuration guide, exquisite development experience
Ali! Visual computing developer's series of manuals (with internet disk link)
Get PMP certificate at 51CTO College
Don't look! Full interpretation of Alibaba cloud's original data lake system! (Internet disk link attached)
2018中国云厂商TOP5:阿里云、腾讯云、AWS、电信、联通 ...