Guava Study Notes (2): Preconditions Elegant test parameters

Source: Internet
Author: User
Tags throw exception

Transferred from: http://www.cnblogs.com/peida/p/Guava_Preconditions.html

In the daily development, we often do some data format validation on the input parameters of the method, in order to ensure that the method can be executed according to the normal process. For some predictable errors on the data, we must do pre-detection and judgment, to avoid program flow error, rather than completely through error processing to ensure that the process is correctly executed, after all, error handling is the way to compare consumption of resources. In the ordinary case, we have to judge the parameters of their own to write a method to judge, the code is quite large and the reusability is not high, as follows:

Import Org.junit.test;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 ("parameter input wrong! ");        }    }}

Description: Parameter validation, we have to add an if statement every time to make judgments, repeated work will be done several times. The Getperson method has only 2 parameters, the validation rules are not very complicated, if the parameters are too much, the validation rules are complicated, the readability of the above code will be very poor, the reusability is much less.

The

Guava Class Library provides a tool class--preconditions class for parameter checking,  This class can greatly simplify the pre-judgment and processing of parameters in our code, allowing us to implement the validation of method input parameters more simply and elegantly, Let's look at the usages of the preconditions class:

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.check        Notnull (Neme, "Neme is null");        Preconditions.checkargument (Neme.length () >0, "Neme for \ '");        Preconditions.checkargument (age>0, "age must be greater than 0"); System.out.println ("A person Age:" +age+ ", Neme: "+neme); }}

Operation Result:

A person age:8,neme:peidaage must be greater than 0neme for ' neme is null '

  Preconditions inside the method:

  1. Checkargument (Boolean):
Function Description: Checks if the Boolean is true. Used as a check parameter in a method
Exception type thrown on failure: illegalargumentexception

  2.checkNotNull (T):
Function Description: Check that value is not null and return value directly;
Exception type thrown on failure: nullpointerexception

 3.checkState (Boolean):
Function Description: Check some states of an object, not dependent on method parameters. For example, iterator can be used to see if Next is called before remove.
Exception type thrown on failure: illegalstateexception

 4.checkElementIndex (int index, int size):
Function Description: Check whether index is a valid range for a list, string, or array of size in length. The range of index is [0, size] (contains 0 does not contain size). No need to pass directly to list, string or array, just pass in the size. Returns index.
Exception type thrown on failure: indexoutofboundsexception


  5.checkPositionIndex (int index, int size):
Function Description: Check if index is a valid range for a list, string, or array of size in length. The range of index is [0, size] (contains 0 does not contain size). No need to pass directly to list, string or array, just pass in the size. Returns index.
Exception type thrown on failure: indexoutofboundsexception

 6.checkPositionIndexes (int start, int end, int size):
Function Description: Check [start, end] is a list of size, string or array valid range subset. Along with the error message.
Exception type thrown on failure: indexoutofboundsexception

A more practical example:

Import Java.util.arraylist;import java.util.list;import Org.junit.test;import com.google.common.base.Preconditions ;p Ublic class Preconditionstest {@Test public void preconditions () throws Exception {Getperson                Byprecondition (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.checkn        Otnull (Neme, "Neme is null");        Preconditions.checkargument (Neme.length () >0, "Neme for \ '");        Preconditions.checkargument (age>0, "age must be greater than 0");             System.out.println ("A person of Age:" +age+ ", Neme:" +neme);        } public static void CheckState (List<integer> intlist,int index) throws exception{//Expression true no throw exception    Preconditions.checkstate (Intlist.size () <index, "intlist size cannot be greater than" +index); } public static void Checkpositionindex (List<integer> intlist,int index) throws exception{Preconditio    Ns.checkpositionindex (Index, Intlist.size (), "index" +index+ "not in 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{precondition    S.checkelementindex (Index, Intlist.size (), "Index is" +index+ "is not in list, list size is:" +intlist.size ()); }}

Output Result:

A person age:8,neme:peidaage must be greater than 0neme for ' neme is null intlist size cannot be greater than 9index 13 not in list, list size is: 9 (in) must not is Grea  ter than size (9) End index (+) must not being greater than size (9) Start index (must not being greater than size (9) index is 16 Not in list, List size: 9 (+) must is less than size (9)

Guava's preconditions has several advantages:

After the static import, the method is very clear and unambiguous, checknotnull can clearly tell you what it is doing, it will throw what kind of exception.
Checknotnull is returned directly after validation, so it is easy to write code: This.field = checknotnull (field).
Simple and powerful variable parameter ' printf ' style custom error message.

Guava Study Notes (2): Preconditions Elegant test parameters

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.