减少该死的 if else 嵌套

落日映苍穹つ 2022-03-08 02:12 213阅读 0赞

来源:https://www.jianshu.com/p/57c065b124c4

1240

写在前面

不知大家有没遇到过像“横放着的金字塔”一样的if else嵌套:

  1. if (true) {
  2. if (true) {
  3. if (true) {
  4. if (true) {
  5. if (true) {
  6. if (true) {
  7. }
  8. }
  9. }
  10. }
  11. }
  12. }

我并没夸大其词,我是真的遇到过了!嵌套6、7层,一个函数几百行,简!直!看!死!人!

if else作为每种编程语言都不可或缺的条件语句,我们在编程时会大量的用到。但if else一般不建议嵌套超过三层,如果一段代码存在过多的if else嵌套,代码的可读性就会急速下降,后期维护难度也大大提高。所以,我们程序员都应该尽量避免过多的if else嵌套。下面将会谈谈我在工作中如何减少if else嵌套的。

正文

在谈我的方法之前,不妨先用个例子来说明if else嵌套过多的弊端。

想象下一个简单分享的业务需求:支持分享链接、图片、文本和图文,分享结果回调给用户(为了不跑题,这里简略了业务,实际复杂得多)。当接手到这么一个业务时,是不是觉得很简单,稍动下脑就可以动手了:

先定义分享的类型、分享Bean和分享回调类:

  1. private static final int TYPE_LINK = 0;
  2. private static final int TYPE_IMAGE = 1;
  3. private static final int TYPE_TEXT = 2;
  4. private static final int TYPE_IMAGE_TEXT = 3;
  5. public class ShareItem {
  6. int type;
  7. String title;
  8. String content;
  9. String imagePath;
  10. String link;
  11. }
  12. public interface ShareListener {
  13. int STATE_SUCC = 0;
  14. int STATE_FAIL = 1;
  15. void onCallback(int state, String msg);
  16. }

好了,然后在定义个分享接口,对每种类型分别进行分享就ok了:

  1. public void share (ShareItem item, ShareListener listener) {
  2. if (item != null) {
  3. if (item.type == TYPE_LINK) {
  4. // 分享链接
  5. if (!TextUtils.isEmpty(item.link) && !TextUtils.isEmpty(item.title)) {
  6. doShareLink(item.link, item.title, item.content, listener);
  7. } else {
  8. if (listener != null) {
  9. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  10. }
  11. }
  12. } else if (item.type == TYPE_IMAGE) {
  13. // 分享图片
  14. if (!TextUtils.isEmpty(item.imagePath)) {
  15. doShareImage(item.imagePath, listener);
  16. } else {
  17. if (listener != null) {
  18. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  19. }
  20. }
  21. } else if (item.type == TYPE_TEXT) {
  22. // 分享文本
  23. if (!TextUtils.isEmpty(item.content)) {
  24. doShareText(item.content, listener);
  25. } else {
  26. if (listener != null) {
  27. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  28. }
  29. }
  30. } else if (item.type == TYPE_IMAGE_TEXT) {
  31. // 分享图文
  32. if (!TextUtils.isEmpty(item.imagePath) && !TextUtils.isEmpty(item.content)) {
  33. doShareImageAndText(item.imagePath, item.content, listener);
  34. } else {
  35. if (listener != null) {
  36. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  37. }
  38. }
  39. } else {
  40. if (listener != null) {
  41. listener.onCallback(ShareListener.STATE_FAIL, "不支持的分享类型");
  42. }
  43. }
  44. } else {
  45. if (listener != null) {
  46. listener.onCallback(ShareListener.STATE_FAIL, "ShareItem 不能为 null");
  47. }
  48. }
  49. }

到此,简单的分享模型就做出来了。有没问题?老实说,如果没什么追求的话,还真没什么问题,至少思路是清晰的。但一周后呢?一个月后呢?或者一年后呢?share方法的分支有15条,这意味着你每次回看代码得让自己的大脑变成微型的处理器,考虑15种情况。如果出现bug,你又得考虑15种情况,并15种情况都要测试下。再如果现在需要加多分享小视频功能,你又得添加多3个分支,还要改代码,一点都不“开放-闭合”。再再如果后面项目交接给他人跟进,他人又要把自己大脑变成处理器来想每个分支的作用,我敢肯定有百分之八十的人都会吐槽代码。

我们程序员的脑力不应该花费在无止境的分支语句里的,应该专注于业务本身。所以我们很有必要避免写出多分支嵌套的语句。好的,我们来分析下上面的代码多分支的原因:

空值判断

业务判断

状态判断

几乎所有的业务都离不开这几个判断,从而导致if else嵌套过多。那是不是没办法解决了?答案肯定不是的。

上面的代码我是用java写的,对于java程序员来说,空值判断简直使人很沮丧,让人身心疲惫。上面的代码每次回调都要判断一次listener是否为空,又要判断用户传入的ShareItem是否为空,还要判断ShareItem里面的字段是否为空……

对于这种情况,我采用的方法很简单:接口分层。

减少 if else 方法一:接口分层

所谓接口分层指的是:把接口分为外部和内部接口,所有空值判断放在外部接口完成,只处理一次;而内部接口传入的变量由外部接口保证不为空,从而减少空值判断。

来,看代码更加直观:

  1. public void share(ShareItem item, ShareListener listener) {
  2. if (item == null) {
  3. if (listener != null) {
  4. listener.onCallback(ShareListener.STATE_FAIL, "ShareItem 不能为 null");
  5. }
  6. return;
  7. }
  8. if (listener == null) {
  9. listener = new ShareListener() {
  10. @Override
  11. public void onCallback(int state, String msg) {
  12. Log.i("DEBUG", "ShareListener is null");
  13. }
  14. };
  15. }
  16. shareImpl(item, listener);
  17. }
  18. private void shareImpl (ShareItem item, ShareListener listener) {
  19. if (item.type == TYPE_LINK) {
  20. // 分享链接
  21. if (!TextUtils.isEmpty(item.link) && !TextUtils.isEmpty(item.title)) {
  22. doShareLink(item.link, item.title, item.content, listener);
  23. } else {
  24. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  25. }
  26. } else if (item.type == TYPE_IMAGE) {
  27. // 分享图片
  28. if (!TextUtils.isEmpty(item.imagePath)) {
  29. doShareImage(item.imagePath, listener);
  30. } else {
  31. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  32. }
  33. } else if (item.type == TYPE_TEXT) {
  34. // 分享文本
  35. if (!TextUtils.isEmpty(item.content)) {
  36. doShareText(item.content, listener);
  37. } else {
  38. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  39. }
  40. } else if (item.type == TYPE_IMAGE_TEXT) {
  41. // 分享图文
  42. if (!TextUtils.isEmpty(item.imagePath) && !TextUtils.isEmpty(item.content)) {
  43. doShareImageAndText(item.imagePath, item.content, listener);
  44. } else {
  45. listener.onCallback(ShareListener.STATE_FAIL, "分享信息不完整");
  46. }
  47. } else {
  48. listener.onCallback(ShareListener.STATE_FAIL, "不支持的分享类型");
  49. }
  50. }

可以看到,上面的代码分为外部接口share和内部接口shareImpl,ShareItem和ShareListener的判断都放在share里完成,那么shareImpl就减少了if else的嵌套了,相当于把if else分摊了。这样一来,代码的可读性好很多,嵌套也不超过3层了。

但可以看到,shareImpl里还是包含分享类型的判断,也即业务判断,我们都清楚产品经理的脑洞有多大了,分享的类型随时会改变或添加。嗯说到这里相信大家都想到用多态了。多态不但能应付业务改变的情况,也可以用来减少if else的嵌套。

减少 if else 方法二:多态

利用多态,每种业务单独处理,在接口不再做任何业务判断。把ShareItem抽象出来,作为基础类,然后针对每种业务各自实现其子类:

  1. public abstract class ShareItem {
  2. int type;
  3. public ShareItem(int type) {
  4. this.type = type;
  5. }
  6. public abstract void doShare(ShareListener listener);
  7. }
  8. public class Link extends ShareItem {
  9. String title;
  10. String content;
  11. String link;
  12. public Link(String link, String title, String content) {
  13. super(TYPE_LINK);
  14. this.link = !TextUtils.isEmpty(link) ? link : "default";
  15. this.title = !TextUtils.isEmpty(title) ? title : "default";
  16. this.content = !TextUtils.isEmpty(content) ? content : "default";
  17. }
  18. @Override
  19. public void doShare(ShareListener listener) {
  20. // do share
  21. }
  22. }
  23. public class Image extends ShareItem {
  24. String imagePath;
  25. public Image(String imagePath) {
  26. super(TYPE_IMAGE);
  27. this.imagePath = !TextUtils.isEmpty(imagePath) ? imagePath : "default";
  28. }
  29. @Override
  30. public void doShare(ShareListener listener) {
  31. // do share
  32. }
  33. }
  34. public class Text extends ShareItem {
  35. String content;
  36. public Text(String content) {
  37. super(TYPE_TEXT);
  38. this.content = !TextUtils.isEmpty(content) ? content : "default";
  39. }
  40. @Override
  41. public void doShare(ShareListener listener) {
  42. // do share
  43. }
  44. }
  45. public class ImageText extends ShareItem {
  46. String content;
  47. String imagePath;
  48. public ImageText(String imagePath, String content) {
  49. super(TYPE_IMAGE_TEXT);
  50. this.imagePath = !TextUtils.isEmpty(imagePath) ? imagePath : "default";
  51. this.content = !TextUtils.isEmpty(content) ? content : "default";
  52. }
  53. @Override
  54. public void doShare(ShareListener listener) {
  55. // do share
  56. }
  57. }

(注意:上面每个子类的构造方法还对每个字段做了空值处理,为空的话,赋值default,这样如果用户传了空值,在调试就会发现问题。)

实现了多态后,分享接口的就简洁多了:

  1. public void share(ShareItem item, ShareListener listener) {
  2. if (item == null) {
  3. if (listener != null) {
  4. listener.onCallback(ShareListener.STATE_FAIL, "ShareItem 不能为 null");
  5. }
  6. return;
  7. }
  8. if (listener == null) {
  9. listener = new ShareListener() {
  10. @Override
  11. public void onCallback(int state, String msg) {
  12. Log.i("DEBUG", "ShareListener is null");
  13. }
  14. };
  15. }
  16. shareImpl(item, listener);
  17. }
  18. private void shareImpl (ShareItem item, ShareListener listener) {
  19. item.doShare(listener);
  20. }

嘻嘻,怎样,内部接口一个if else都没了,是不是很酷~ 如果这个分享功能是自己App里面的功能,不是第三方SDK,到这里已经没问题了。但如果是第三方分享SDK的功能的话,这样暴露给用户的类增加了很多(各ShareItem的子类,相当于把if else抛给用户了),用户的接入成本提高,违背了“迪米特原则”了。

处理这种情况也很简单,再次封装一层即可。把ShareItem的子类的访问权限降低,在暴露给用户的主类里定义几个方法,在内部帮助用户创建具体的分享类型,这样用户就无需知道具体的类了:

  1. public ShareItem createLinkShareItem(String link, String title, String content) {
  2. return new Link(link, title, content);
  3. }
  4. public ShareItem createImageShareItem(String ImagePath) {
  5. return new Image(ImagePath);
  6. }
  7. public ShareItem createTextShareItem(String content) {
  8. return new Text(content);
  9. }
  10. public ShareItem createImageTextShareItem(String ImagePath, String content) {
  11. return new ImageText(ImagePath, content);
  12. }

或者有人会说,这样用户也需额外了解多几个方法。我个人觉得让用户了解多几个方法好过了解多几个类,而已方法名一看就能知道意图,成本还是挺小,是可以接受的。

其实这种情况,更多人想到的是使用工厂模式。嗯,工厂模式能解决这个问题(其实也需要用户额外了解多几个type类型),但工厂模式难免又引入分支,我们可以用Map消除分支。

减少 if else 方法三:使用Map替代分支语句

把所有分享类型预先缓存在Map里,那么就可以直接get获取具体类型,消除分支:

  1. private Map<Integer, Class<? extends ShareItem>> map = new HashMap<>();
  2. private void init() {
  3. map.put(TYPE_LINK, Link.class);
  4. map.put(TYPE_IMAGE, Image.class);
  5. map.put(TYPE_TEXT, Text.class);
  6. map.put(TYPE_IMAGE_TEXT, ImageText.class);
  7. }
  8. public ShareItem createShareItem(int type) {
  9. try {
  10. Class<? extends ShareItem> shareItemClass = map.get(type);
  11. return shareItemClass.newInstance();
  12. } catch (Exception e) {
  13. return new DefaultShareItem(); // 返回默认实现,不要返回null
  14. }
  15. }

这种方式跟上面分为几个方法的方式各有利弊,看大家取舍了~

写在最后

讲到这里大家有没收获呢?总结下减少if else的方法

把接口分为外部和内部接口,所有空值判断放在外部接口完成;而内部接口传入的变量由外部接口保证不为空,从而减少空值判断。

利用多态,把业务判断消除,各子类分别关注自己的实现,并实现子类的创建方法,避免用户了解过多的类。

把分支状态信息预先缓存在Map里,直接get获取具体值,消除分支。

好了,到此就介绍完了,希望大家以后写代码能注意,有则避之,无则加勉。希望大家写的代码越来越简洁~

扩展阅读

面试的时候问:你的期望薪资多少?怎么谈?

MySQL到底有多少种日志类型需要我们记住的!

僧多肉少的阿里实习,我面了5次才拿到offer!

这20个正则表达式,让你少写1,000行代码

全面对比 Redis 和 Memcached 的 6 点区别

70

发表评论

表情:
评论列表 (有 0 条评论,213人围观)

还没有评论,来说两句吧...

相关阅读