当前位置:网站首页>Eight ways to optimize if else code

Eight ways to optimize if else code

2020-11-08 12:11:41 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

     Optimize if-else Eight schemes of code

  • 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:]所创,转载请带上原文链接,感谢