我们的目的是简化代码缩进
很多时候我们写代码会写成这样:
public void mothodName(String... args) {
// some code here
if (booleanVariable) {
// do a lot of things
// do a lot of things
// do a lot of things
// do a lot of things
// do a lot of things
} else {
// do something
}
}
这样的代码缩进会比较多,尤其在if里面的代码非常多的时候,我们再去找else时,也比较费劲
我们需要改进这段代码
public void mothodName(String... args) {
// some code here
if (booleanVariable) {
} else {
// do something
return;
}
// do a lot of things
// do a lot of things
// do a lot of things
// do a lot of things
// do a lot of things
}
如上, 第一步,我们加了一个return,然后把if中的代码复制到else后面,这样代码看起来就不一样了
当然上面的代码在if-else处还可以做如下修改:
public void mothodName(String... args) {
// some code here
if (!booleanVariable) {
// do something
return;
}
// do a lot of things
// do a lot of things
// do a lot of things
// do a lot of things
// do a lot of things
}
这样就完美了
精简代码缩进,提升阅读体验
本文旨在展示如何通过调整代码结构和使用return语句来减少代码缩进,提高代码可读性和查找效率。具体操作包括将if条件块内的代码移到else块之后,并在if条件为假时直接返回,从而实现代码简洁化。
1229

被折叠的 条评论
为什么被折叠?



