詳解Java如何簡化條件表達式
在復雜的實際業(yè)務中,往往會出現(xiàn)各種嵌套的條件判斷邏輯。我們需要考慮所有可能的情況。隨著需求的增加,條件邏輯會變得越來越復雜,判斷函數(shù)會變的相當長,而且也不能輕易修改這些代碼。每次改需求的時候,都要保證所有分支邏輯判斷的情況都改了。
面對這種情況,簡化判斷邏輯就是不得不做的事情,下面介紹幾種方法。
一個實際例子
@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;
}上面的例子是一個文件下載功能。我們根據(jù)用戶需要下載Excel、CSV或TXT文件。下載之前需要做一些合法性判斷,比如驗證用戶權限,驗證請求文件的格式。
使用斷言
在上面的例子中,有四層嵌套。但是最外層的兩層嵌套是為了驗證參數(shù)的有效性。只有條件為真時,代碼才能正常運行。可以使用斷言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();
}
}可以看出在使用斷言之后,代碼的可讀性更高了。代碼可以分成兩部分,一部分是參數(shù)校驗邏輯,另一部分是文件下載功能。
表驅動
斷言可以優(yōu)化一些條件表達式,但還不夠好。我們仍然需要通過判斷filetype屬性來確定要下載的文件格式。假設現(xiàn)在需求有變化,需要支持word格式文件的下載,那我們就需要直接改這塊的代碼,實際上違反了開閉原則。
表驅動可以解決這個問題。
private HashMap<String, Consumer> 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就可以了。
使用枚舉
除了表驅動,我們還可以使用枚舉來優(yōu)化條件表達式,將各種邏輯封裝在具體的枚舉實例中。這同樣可以提高代碼的可擴展性。其實Enum本質上就是一種表驅動的實現(xiàn)。(kotlin中可以使用sealed class處理這個問題,只不過具實現(xiàn)方法不太一樣)
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
}
}
@Autowired
private List<FileDownload> 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簡化判斷邏輯內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Java Web項目中Spring框架處理JSON格式數(shù)據(jù)的方法
Spring MVC是個靈活的框架,返回JSON數(shù)據(jù)的也有很多五花八門的方式,這里我們來整理一個最簡單的Java Web項目中Spring框架處理JSON格式數(shù)據(jù)的方法:2016-05-05
詳解Java中多線程異常捕獲Runnable的實現(xiàn)
這篇文章主要介紹了詳解Java中多線程異常捕獲Runnable的實現(xiàn)的相關資料,希望通過本文能幫助到大家,讓大家理解掌握這樣的知識,需要的朋友可以參考下2017-10-10
Java使用JDBC或MyBatis框架向Oracle中插入XMLType數(shù)據(jù)
XMLType是Oracle支持的一種基于XML格式存儲的數(shù)據(jù)類型,這里我們共同來探究Java使用JDBC或MyBatis框架向Oracle中插入XMLType數(shù)據(jù)的方法:2016-07-07
JavaWeb response和request對象原理及實例解析
這篇文章主要介紹了JavaWeb response和request對象原理及實例解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-11-11
Mybatis中的resultType和resultMap使用
這篇文章主要介紹了Mybatis中的resultType和resultMap使用,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-09-09

