首页 热点 业界 科技快讯 数码 电子消费 通信 前沿动态 电商

详解Java如何简化条件表达式

2022-06-10 09:37:38 来源 : 软件开发网

目录

一个实际例子

使用断言

表驱动

使用枚举

策略模式

在复杂的实际业务中,往往会出现各种嵌套的条件判断逻辑。我们需要考虑所有可能的情况。随着需求的增加,条件逻辑会变得越来越复杂,判断函数会变的相当长,而且也不能轻易修改这些代码。每次改需求的时候,都要保证所有分支逻辑判断的情况都改了。

面对这种情况,简化判断逻辑就是不得不做的事情,下面介绍几种方法。

一个实际例子@GetMapping("/exportOrderRecords")public void downloadFile(User user, HttpServletResponse response) { if (user != null) { if (!StringUtils.isBlank(user.role) && authenticate(user.role)) { String fileType = user.getFileType(); // 获得文件类型 if (!StringUtils.isBlank(fileType)) { if (fileType.equalsIgnoreCase("csv")) { doDownloadCsv(); // 不同类型文件的下载策略 } else if (fileType.equalsIgnoreCase("excel")) { doDownloadExcel(); // 不同类型文件的下载策略 } else { doDownloadTxt(); // 不同类型文件的下载策略 } } else { doDownloadCsv(); } } }}public class User { private String username; private String role; private String fileType;}

上面的例子是一个文件下载功能。我们根据用户需要下载Excel、CSV或TXT文件。下载之前需要做一些合法性判断,比如验证用户权限,验证请求文件的格式。

使用断言

在上面的例子中,有四层嵌套。但是最外层的两层嵌套是为了验证参数的有效性。只有条件为真时,代码才能正常运行。可以使用断言Assert.isTrue()。如果断言不为真的时候抛出RuntimeException。(注意要注明会抛出异常,kotlin中也一样)

@GetMapping("/exportOrderRecords")public void downloadFile(User user, HttpServletResponse response) throws Exception { Assert.isTrue(user != null, "the request body is required!"); Assert.isTrue(StringUtils.isNotBlank(user.getRole()), "download file is for"); Assert.isTrue(authenticate(user.getRole()), "you do not have permission to download files"); String fileType = user.getFileType(); if (!StringUtils.isBlank(fileType)) { if (fileType.equalsIgnoreCase("csv")) { doDownloadCsv(); } else if (fileType.equalsIgnoreCase("excel")) { doDownloadExcel(); } else { doDownloadTxt(); } } else { doDownloadCsv(); }}

可以看出在使用断言之后,代码的可读性更高了。代码可以分成两部分,一部分是参数校验逻辑,另一部分是文件下载功能。

表驱动

断言可以优化一些条件表达式,但还不够好。我们仍然需要通过判断filetype属性来确定要下载的文件格式。假设现在需求有变化,需要支持word格式文件的下载,那我们就需要直接改这块的代码,实际上违反了开闭原则。

表驱动可以解决这个问题。

private HashMap map = new HashMap<>();public Demo() { map.put("csv", response -> doDownloadCsv()); map.put("excel", response -> doDownloadExcel()); map.put("txt", response -> doDownloadTxt());}@GetMapping("/exportOrderRecords")public void downloadFile(User user, HttpServletResponse response) { Assert.isTrue(user != null, "the request body is required!"); Assert.isTrue(StringUtils.isNotBlank(user.getRole()), "download file is for"); Assert.isTrue(authenticate(user.getRole()), "you do not have permission to download files"); String fileType = user.getFileType(); Consumer consumer = map.get(fileType); if (consumer != null) { consumer.accept(response); } else { doDownloadCsv(); }}

可以看出在使用了表驱动之后,如果想要新增类型,只需要在map中新增一个key-value就可以了。

使用枚举

除了表驱动,我们还可以使用枚举来优化条件表达式,将各种逻辑封装在具体的枚举实例中。这同样可以提高代码的可扩展性。其实Enum本质上就是一种表驱动的实现。(kotlin中可以使用sealed class处理这个问题,只不过具实现方法不太一样)

public enum FileType { EXCEL(".xlsx") { @Override public void download() { } }, CSV(".csv") { @Override public void download() { } }, TXT(".txt") { @Override public void download() { } }; private String suffix; FileType(String suffix) { this.suffix = suffix; } public String getSuffix() { return suffix; } public abstract void download();}@GetMapping("/exportOrderRecords")public void downloadFile(User user, HttpServletResponse response) { Assert.isTrue(user != null, "the request body is required!"); Assert.isTrue(StringUtils.isNotBlank(user.getRole()), "download file is for"); Assert.isTrue(authenticate(user.getRole()), "you do not have permission to download files"); String fileType = user.getFileType(); FileType type = FileType.valueOf(fileType); if (type!=null) { type.download(); } else { FileType.CSV.download(); }}策略模式

我们还可以使用策略模式来简化条件表达式,将不同文件格式的下载处理抽象成不同的策略类。

public interface FileDownload{ boolean support(String fileType); void download(String fileType);}public class CsvFileDownload implements FileDownload{ @Override public boolean support(String fileType) { return "CSV".equalsIgnoreCase(fileType); } @Override public void download(String fileType) { if (!support(fileType)) return; // do something }}public class ExcelFileDownload implements FileDownload { @Override public boolean support(String fileType) { return "EXCEL".equalsIgnoreCase(fileType); } @Override public void download(String fileType) { if (!support(fileType)) return; //do something }}@Autowiredprivate List fileDownloads;@GetMapping("/exportOrderRecords")public void downloadFile(User user, HttpServletResponse response) { Assert.isTrue(user != null, "the request body is required!"); Assert.isTrue(StringUtils.isNotBlank(user.getRole()), "download file is for"); Assert.isTrue(authenticate(user.getRole()), "you do not have permission to download files"); String fileType = user.getFileType(); for (FileDownload fileDownload : fileDownloads) { fileDownload.download(fileType); }}

到此这篇关于详解Java如何简化判断逻辑的文章就介绍到这了,更多相关Java简化判断逻辑内容请搜索软件开发网以前的文章或继续浏览下面的相关文章希望大家以后多多支持软件开发网!

标签: 条件表达式 文件格式 可以看出

相关文章

最近更新
观焦点:超萌相机 2023-03-01 12:29:37
海南百货网 2023-03-01 12:13:44
焦点热讯:宜点充 2023-02-28 10:10:16
天天关注:小铺CEO 2023-02-28 10:07:13
【世界聚看点】KaFit 2023-02-28 09:31:37
葱天下 2023-02-28 09:17:03
渔界竞钓 2023-02-28 08:15:29
焦点快看:鲸奇视频 2023-02-28 06:30:37
环球热议:萝小逗 2023-02-27 23:25:49
简讯:小码公交 2023-02-27 23:16:12
彼岸花 2023-02-27 22:32:52
时时夺宝 2023-02-27 21:37:50
天天动态:袜之源 2023-02-27 21:29:50
天天资讯:AI空气 2023-02-27 20:19:46
世界时讯:绘读 2023-02-27 20:19:41
看点:一元得购 2023-02-27 19:26:28