Foreword
Some time ago while reading the code written by others, I found some of the in vivo method in which business-related, there has been a number of if-else
cases of nested statements. First, I personally do not advocate not write the if-else
statement, had said many times, in some write logic used if-else
to do determination, or the code looks very straightforward, but if abused if-else
, or nested formed is formed, wherein each case further contains a large amount of logic, the case for readability, use if-else
a bit more harm than good. and sometimes, may not need so much if-else
, or may use other coding method so as to achieve reduction if-else
effect.
Reduction if-else
method used There are many design patterns such as the level of strategy pattern or chain of responsibility pattern . And here to share with you some personal daily encoding process frequently used, relatively simple, from the level of coding habits the way , to reduce the number of unnecessary if-else
use. Since I was just a little rookie, if you have not written the place, I implore criticism.
Some reduction encoding if-else
One way: advance return
First piece of code examples show:
if (condition1) {
if (condition2) {
return getSomething();
} else {
return 0;
}
} else {
return 0;
}
复制代码
The modified code as follows:
//这里最好对这个flag所判断的逻辑补充注释进行描述
boolean flag = !condition1 || (condition1 && !condition2)
if(flag) {
return 0;
}
if (condition1 && condition2) {
return getSomething();
}
复制代码
If it is known that under certain conditions, need to return a fixed logic value, this part can be extracted as a logically independent existence if-else block
, and the other is placed if-else block
in front, when that meet certain conditions, directly ahead of return
this fixed value. the most direct effect is to reduce if-else
the number of nesting.
Second way: ternary operator using
The first example, here's to a business scenario as an example:
Image URL query about a review of the list (if there is, the picture url list Save comment in the comments to table an array of JSON string format)
Code before modification as follows:
Comment comment = getById(commentId);
if (Objects.isNull(comment)) {
throw new RuntimeException("评论不存在或已被删除");
}
String imgListStr = comment.getImgList();
if(StringUtils.isEmpty(imgListStr)) {
return null;
}
return JSON.parseArray(imgListStr, String.class);
复制代码
Modified:
Comment comment = getById(commentId);
if (Objects.isNull(comment)) {
throw new RuntimeException("评论不存在或已被删除");
}
String imgListStr = comment.getImgList();
return StringUtils.isEmpty(imgListStr)) ?
null : JSON.parseArray(imgListStr, String.class);
复制代码
Three ways: using Assert assertion
In preparing the business code, if required for certain specific conditions is determined, and when the condition is not satisfied needs to throw an exception. For this scenario, using the above example except ternary operator among if
manner, can also using the Spring Framework provides us with the Assert
tools classes.
API which are commonly used are:
- isTrue (boolean expression, String message) : When
expressio == false
the time, will throw an exception, the exceptionmessage
was the second to the Senate; - void notNull (@Nullable Object object, String message): as above, when
object == null
the time will throw an exception; - void notEmpty (<?> @Nullable Collection collection, String message): as above, when the object is a collection
null
or when the collection element is empty, an exception is thrown. - .....
There are many other ways you can look at the source code directly to resolve, of course, in fact, isTrue()
has been good enough, if you need more semantic, you can use the corresponding API.
Modify the code before:
if (Objects.isNull(comment)) {
throw new RuntimeException("评论不存在或已被删除");
}
复制代码
After modifying the code:
Assert.isTrue(Objects.nonNull(comment),"评论不存在或已被删除");
Assert.notNull(comment,"评论不存在或已被删除");
复制代码
Currently Assert method can throw only a single tool for an unusual java.lang.IllegalArgumentException
, if you need to customize the thrown exception, then the way is not applicable.
Four ways: Use Optional
Optional java8 is a new feature of an object corresponding to the container , the main object for the null
values of the check, and the chain can be performed after performing the subsequent operation check, such as: an exception is thrown, null
replacement and the like.
Which I personally used several methods:
- static <T> Optional <T> ofNullable (T value): Use Optional wrapped object;
- OrElse T (T OTHER): Optional The object is
null
, the return into the reference object. - OrElseGet T (<? T the extends> Supplier OTHER): Optional The object is
null
, the returnSupplier
value is provided; - OrElseThrow T (Supplier exceptionSupplier <the extends the X-?>): Optional The object
null
is thrownsupplier
custom exception provided
Code Example:
Message message1 = Optional.ofNullable(getById(messageId))
.orElseThrow(() -> new RuntimeException("消息不存在!"));
Message message2 = Optional.ofNullable(getById(messageId))
.orElse(new Message());
Message message3 = Optional.ofNullable(getById(messageId))
.orElseGet(Message::new);
复制代码
Because I need to be more everyday scenes null value judgment is completed when the data from a database query, the query results need to be a null value judgment. Since the persistence framework my company using mybatis, unlike Spirng Boot 2.x JPA DAO layer method as the default version supports the return value is Optional, so here If you need Optional, only manually to use the first method listed above query results package.
Of course, IDEA is already provided us with the packaging of a hot key, as shown below:
Epilogue
Some individuals reduce if-else
coding practices shared on here, and this in several ways, and I personally feel that the most obvious effect is the first advance return , many times, well ahead of return can reduce the complexity of a piece of code.
Of course, if you have to use a lot of if-else
time to control logic, indicate what the comment was a very good habit in every condition.