最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

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

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

前言:

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

面對(duì)這種情況,簡(jiǎ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;
}

上面的例子是一個(gè)文件下載功能。我們根據(jù)用戶需要下載Excel、CSV或TXT文件。下載之前需要做一些合法性判斷,比如驗(yàn)證用戶權(quán)限,驗(yàn)證請(qǐng)求文件的格式。

使用方法

在上面的例子中,有四層嵌套。但是最外層的兩層嵌套是為了驗(yàn)證參數(shù)的有效性。只有條件為真時(shí),代碼才能正常運(yùn)行。可以使用斷言Assert.isTrue()。如果斷言不為真的時(shí)候拋出RuntimeException。(注意要注明會(huì)拋出異常,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ū)動(dòng)

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

表驅(qū)動(dòng)可以解決這個(gè)問題:

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ū)動(dòng)之后,如果想要新增類型,只需要在map中新增一個(gè)key-value就可以了。

使用枚舉

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

策略模式

我們還可以使用策略模式來簡(jiǎn)化條件表達(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);
    }
}

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

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

相關(guān)文章

  • Android drawable微技巧,你不知道的drawable細(xì)節(jié)

    Android drawable微技巧,你不知道的drawable細(xì)節(jié)

    今天小編就為大家分享一篇關(guān)于Android drawable微技巧,你不知道的drawable細(xì)節(jié),小編覺得內(nèi)容挺不錯(cuò)的,現(xiàn)在分享給大家,具有很好的參考價(jià)值,需要的朋友一起跟隨小編來看看吧
    2018-10-10
  • Android數(shù)據(jù)流之Channel和Flow實(shí)現(xiàn)原理和技巧詳解

    Android數(shù)據(jù)流之Channel和Flow實(shí)現(xiàn)原理和技巧詳解

    在 Android 應(yīng)用程序的開發(fā)中,處理異步數(shù)據(jù)流是一個(gè)常見的需求,為了更好地應(yīng)對(duì)這些需求,Kotlin 協(xié)程引入了 Channel 和 Flow,它們提供了強(qiáng)大的工具來處理數(shù)據(jù)流,本文將深入探討 Channel 和 Flow 的內(nèi)部實(shí)現(xiàn)原理、高級(jí)使用技巧以及如何在 Android 開發(fā)中充分利用它們
    2023-11-11
  • sweet alert dialog 在android studio應(yīng)用問題說明詳解

    sweet alert dialog 在android studio應(yīng)用問題說明詳解

    這篇文章主要介紹了sweet alert dialog 在android studio應(yīng)用問題說明詳解的相關(guān)資料,本文圖文并茂介紹的非常詳細(xì),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2016-09-09
  • Compose開發(fā)之動(dòng)畫藝術(shù)探索及實(shí)現(xiàn)示例

    Compose開發(fā)之動(dòng)畫藝術(shù)探索及實(shí)現(xiàn)示例

    這篇文章主要為大家介紹了Compose開發(fā)之動(dòng)畫藝術(shù)探索及實(shí)現(xiàn)示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
    2022-09-09
  • Android?Kotlin?中的groupBy方法詳解

    Android?Kotlin?中的groupBy方法詳解

    在Kotlin中,groupBy函數(shù)可以對(duì)集合進(jìn)行分組,形成一個(gè)Map,其中key是分組標(biāo)準(zhǔn),value是對(duì)應(yīng)的元素列表,本文通過實(shí)例詳細(xì)解釋groupBy的使用方法和常見應(yīng)用場(chǎng)景,如按員工年齡分組或產(chǎn)品類型統(tǒng)計(jì)數(shù)量等,展示了groupBy的靈活性和實(shí)用性
    2024-09-09
  • Android ViewModel與Lifecycles和LiveData組件用法詳細(xì)講解

    Android ViewModel與Lifecycles和LiveData組件用法詳細(xì)講解

    JetPack是一個(gè)開發(fā)組件工具集,他的主要目的是幫助我們編寫出更加簡(jiǎn)潔的代碼,并簡(jiǎn)化我們的開發(fā)過程。JetPack中的組件有一個(gè)特點(diǎn),它們大部分不依賴于任何Android系統(tǒng)版本,這意味者這些組件通常是定義在AndroidX庫當(dāng)中的,并且擁有非常好的向下兼容性
    2023-01-01
  • android實(shí)現(xiàn)掃描網(wǎng)頁二維碼進(jìn)行網(wǎng)頁登錄功能

    android實(shí)現(xiàn)掃描網(wǎng)頁二維碼進(jìn)行網(wǎng)頁登錄功能

    這篇文章主要介紹了android掃描網(wǎng)頁二維碼進(jìn)行網(wǎng)頁登錄效果,掃描成功之后跳轉(zhuǎn)進(jìn)入主頁,具體實(shí)現(xiàn)代碼大家參考下本文
    2017-12-12
  • Android酷炫動(dòng)畫效果之3D星體旋轉(zhuǎn)效果

    Android酷炫動(dòng)畫效果之3D星體旋轉(zhuǎn)效果

    本文要實(shí)現(xiàn)的3D星體旋轉(zhuǎn)效果是從CoverFlow演繹而來,不過CoverFlow只是對(duì)圖像進(jìn)行轉(zhuǎn)動(dòng),我這里要實(shí)現(xiàn)的效果是要對(duì)所有的View進(jìn)行類似旋轉(zhuǎn)木馬的轉(zhuǎn)動(dòng)
    2018-05-05
  • Android編程判斷是否連接網(wǎng)絡(luò)的方法【W(wǎng)iFi及3G判斷】

    Android編程判斷是否連接網(wǎng)絡(luò)的方法【W(wǎng)iFi及3G判斷】

    這篇文章主要介紹了Android編程判斷是否連接網(wǎng)絡(luò)的方法,結(jié)合實(shí)例形式分析了Android針對(duì)WiFi及3G網(wǎng)絡(luò)連接的判斷方法,需要的朋友可以參考下
    2017-02-02
  • 剖析Android Activity側(cè)滑返回的實(shí)現(xiàn)原理

    剖析Android Activity側(cè)滑返回的實(shí)現(xiàn)原理

    在很多的App中,都會(huì)發(fā)現(xiàn)利用手指滑動(dòng)事件,進(jìn)行高效且人性化的交互非常有必要,那么它是怎么實(shí)現(xiàn)的呢,本文給大家解析實(shí)現(xiàn)原理,對(duì)Activity側(cè)滑返回實(shí)現(xiàn)代碼感興趣的朋友一起看看吧
    2021-06-06

最新評(píng)論

绥宁县| 桐梓县| 吴堡县| 元朗区| 彰化市| 手机| 双江| 鲁甸县| 长寿区| 车险| 罗源县| 乌鲁木齐县| 友谊县| 泾阳县| 鸡东县| 张家界市| 新化县| 蒲城县| 双城市| 永定县| 象州县| 平遥县| 青冈县| 龙游县| 新宁县| 阳西县| 邯郸市| 鲜城| 灵石县| 葫芦岛市| 泗阳县| 肥城市| 陆良县| 那坡县| 卢龙县| 西乌| 凤翔县| 广安市| 邵阳市| 中宁县| 田阳县|