欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Android利用Java優(yōu)雅消除復(fù)雜條件表達(dá)式的方法

 更新時間:2022年06月17日 09:04:35   作者:??謝天_bytedance????  
這篇文章主要介紹了Android利用Java優(yōu)雅消除復(fù)雜條件表達(dá)式,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值。感興趣的小伙伴可以參考一下

前言:

在復(fù)雜的實(shí)際業(yè)務(wù)中,往往會出現(xiàn)各種嵌套的條件判斷邏輯。我們需要考慮所有可能的情況。隨著需求的增加,條件邏輯會變得越來越復(fù)雜,判斷函數(shù)會變的相當(dāng)長,而且也不能輕易修改這些代碼。每次改需求的時候,都要保證所有分支邏輯判斷的情況都改了。

面對這種情況,簡化判斷邏輯就是不得不做的事情,下面介紹幾種方法

實(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文件。下載之前需要做一些合法性判斷,比如驗(yàn)證用戶權(quán)限,驗(yàn)證請求文件的格式。

使用方法

在上面的例子中,有四層嵌套。但是最外層的兩層嵌套是為了驗(yàn)證參數(shù)的有效性。只有條件為真時,代碼才能正常運(yùn)行??梢允褂脭嘌?code>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àn)邏輯,另一部分是文件下載功能。

表驅(qū)動

斷言可以優(yōu)化一些條件表達(dá)式,但還不夠好。我們?nèi)匀恍枰ㄟ^判斷filetype屬性來確定要下載的文件格式。假設(shè)現(xiàn)在需求有變化,需要支持word格式文件的下載,那我們就需要直接改這塊的代碼,實(shí)際上違反了開閉原則。

表驅(qū)動可以解決這個問題:

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();
    }
}

可以看出在使用了表驅(qū)動之后,如果想要新增類型,只需要在map中新增一個key-value就可以了。

使用枚舉

除了表驅(qū)動,我們還可以使用枚舉來優(yōu)化條件表達(dá)式,將各種邏輯封裝在具體的枚舉實(shí)例中。這同樣可以提高代碼的可擴(kuò)展性。其實(shí)Enum本質(zhì)上就是一種表驅(qū)動的實(shí)現(xiàn)。(kotlin中可以使用sealed class處理這個問題,只不過具實(shí)現(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();
    }
}

策略模式

我們還可以使用策略模式來簡化條件表達(dá)式,將不同文件格式的下載處理抽象成不同的策略類。

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);
    }
}

策略模式對提高代碼可擴(kuò)展性很有幫助。擴(kuò)展新的類型只需要添加一個策略類。

到此這篇關(guān)于Android利用Java優(yōu)雅消除復(fù)雜條件表達(dá)式的方法的文章就介紹到這了,更多相關(guān)Android條件表達(dá)式內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論