Guava學習筆記:Preconditions優雅的檢驗參數

在平常開發中,咱們常常會對方法的輸入參數作一些數據格式上的驗證,以便保證方法可以按照正常流程執行下去。對於可預知的一些數據上的錯誤,咱們必定要作事前檢測和判斷,來避免程序流程出錯,而不是徹底經過錯誤處理來保證流程正確執行,畢竟錯誤處理是比較消耗資源的方式。在日常狀況下咱們對參數的判斷都須要本身來逐個寫方法判斷,代碼量很多而且複用性不高,以下所示:java

複製代碼 import org.junit.Test;less

public class PreconditionsTest {工具

@Test
public void Preconditions() throws Exception { 
    
    getPerson(8,"peida");
    
    getPerson(-9,"peida");
    
    getPerson(8,"");
    
    getPerson(8,null);
}
public static void getPerson(int age,String neme)throws Exception{
    if(age>0&&neme!=null&&neme.isEmpty()!=true){
        System.out.println("a person age:"+age+",neme:"+neme);
    }else{
        System.out.println("參數輸入有誤!");
    }
}

}this

複製代碼google

  說明:參數驗證,咱們每次都要添加if語句來作判斷, 重複的工做會作好屢次。getPerson方法只有2個參數,驗證規則也不是很複雜,若是參數過分,驗證規則複雜後,上面代碼的可讀性都會不好的,複用性就更談不上了。code

  Guava類庫中提供了一個做參數檢查的工具類--Preconditions類, 該類能夠大大地簡化咱們代碼中對於參數的預判斷和處理,讓咱們對方法輸入參數的驗證明現起來更加簡單優雅,下面咱們看看Preconditions類的使用實例: 對象

複製代碼 import org.junit.Test; import com.google.common.base.Preconditions;資源

public class PreconditionsTest {開發

@Test
public void Preconditions() throws Exception { 
    
    getPersonByPrecondition(8,"peida");
    
    try {
        getPersonByPrecondition(-9,"peida");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        getPersonByPrecondition(8,"");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        getPersonByPrecondition(8,null);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    } 
}

public static void getPersonByPrecondition(int age,String neme)throws Exception{
    Preconditions.checkNotNull(neme, "neme爲null");
    Preconditions.checkArgument(neme.length()>0, "neme爲\'\'");
    Preconditions.checkArgument(age>0, "age 必須大於0");
    System.out.println("a person age:"+age+",neme:"+neme);
}

}rem

複製代碼

  運行結果:

a person age:8,neme:peida age 必須大於0 neme爲'' neme爲null

  Preconditions裏面的方法:

  1 .checkArgument(boolean) :   功能描述:檢查boolean是否爲真。 用做方法中檢查參數   失敗時拋出的異常類型: IllegalArgumentException

  2.checkNotNull(T):
  功能描述:檢查value不爲null, 直接返回value;   失敗時拋出的異常類型:NullPointerException

  3.checkState(boolean):   功能描述:檢查對象的一些狀態,不依賴方法參數。 例如, Iterator能夠用來next是否在remove以前被調用。   失敗時拋出的異常類型:IllegalStateException

  4.checkElementIndex(int index, int size):   功能描述:檢查index是否爲在一個長度爲size的list, string或array合法的範圍。 index的範圍區間是[0, size)(包含0不包含size)。無需直接傳入list, string或array, 只需傳入大小。返回index。
  失敗時拋出的異常類型:IndexOutOfBoundsException

  5.checkPositionIndex(int index, int size):   功能描述:檢查位置index是否爲在一個長度爲size的list, string或array合法的範圍。 index的範圍區間是[0, size)(包含0不包含size)。無需直接傳入list, string或array, 只需傳入大小。返回index。   失敗時拋出的異常類型:IndexOutOfBoundsException

  6.checkPositionIndexes(int start, int end, int size):   功能描述:檢查[start, end)是一個長度爲size的list, string或array合法的範圍子集。伴隨着錯誤信息。   失敗時拋出的異常類型:IndexOutOfBoundsException

  一個比較實用實例:

複製代碼 import java.util.ArrayList; import java.util.List; import org.junit.Test; import com.google.common.base.Preconditions;

public class PreconditionsTest {

@Test
public void Preconditions() throws Exception { 
    
    getPersonByPrecondition(8,"peida");
    
    try {
        getPersonByPrecondition(-9,"peida");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        getPersonByPrecondition(8,"");
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        getPersonByPrecondition(8,null);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    List<Integer> intList=new ArrayList<Integer> ();
    for(int i=0;i<10;i++){            
        try {
            checkState(intList,9);
            intList.add(i);
        } catch (Exception e) {
            System.out.println(e.getMessage());
        }

    }
    
    try {
        checkPositionIndex(intList,3);    
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        checkPositionIndex(intList,13);    
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        checkPositionIndexes(intList,3,7);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        checkPositionIndexes(intList,3,17);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        checkPositionIndexes(intList,13,17);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        checkElementIndex(intList,6);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
    
    try {
        checkElementIndex(intList,16);
    } catch (Exception e) {
        System.out.println(e.getMessage());
    }
}

public static void getPersonByPrecondition(int age,String neme)throws Exception{
    Preconditions.checkNotNull(neme, "neme爲null");
    Preconditions.checkArgument(neme.length()>0, "neme爲\'\'");
    Preconditions.checkArgument(age>0, "age 必須大於0");
    System.out.println("a person age:"+age+",neme:"+neme);
     
}

public static void checkState(List<Integer> intList,int index)throws Exception{
    //表達式爲true不拋異常
    Preconditions.checkState(intList.size()<index, " intList size 不能大於"+index);
}

public static void checkPositionIndex(List<Integer> intList,int index) throws Exception{
    Preconditions.checkPositionIndex(index, intList.size(), "index "+index+" 不在 list中, List size爲:"+intList.size());
}

public static void checkPositionIndexes(List<Integer> intList,int start,int end) throws Exception{
    Preconditions.checkPositionIndexes(start, end, intList.size());
}

public static void checkElementIndex(List<Integer> intList,int index) throws Exception{
    Preconditions.checkElementIndex(index, intList.size(),"index 爲 "+index+" 不在 list中, List size爲: "+intList.size());
}

}

複製代碼

  輸出結果:

複製代碼 a person age:8,neme:peida age 必須大於0 neme爲'' neme爲null intList size 不能大於9 index 13 不在 list中, List size爲:9 (13) must not be greater than size (9) end index (17) must not be greater than size (9) start index (13) must not be greater than size (9) index 爲 16 不在 list中, List size爲: 9 (16) must be less than size (9)

複製代碼

  Guava的preconditions有這樣幾個優勢:

  在靜態導入後, 方法很明確無歧義, checkNotNull能夠清楚地告訴你它是幹什麼的, 它會拋出怎樣的異常.   checkNotNull在驗證經過後直接返回, 能夠這樣方便地寫代碼: this.field = checkNotNull(field). 簡單而又強大的可變參數'printf'風格的自定義錯誤信息.

相關文章
相關標籤/搜索