Preconditions Elegant test parameters

Source: Internet
Author: User

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) {          &Nbsp;  system.out.println ("A person age:" +age+ ", Neme:" +neme);         }else{             SYSTEM.OUT.PRINTLN ("parameter input is 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, which can greatly simplify the pre-judgment and processing of parameters in our code, making it easier and more elegant to validate method input parameters, Let's look at the usage examples 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 {    &Nbsp;       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 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):
Feature Description: Checks if the Boolean is true. The exception type that is thrown when checking for parameter
failure in a method: IllegalArgumentException

2.checkNotNull (T):      
Function Description: Checks that value is not NULL and returns value directly;
Exception type thrown on failure: NullPointerException

3.checkState (Boolean):
Feature Description: Checks some state of an object, independent of 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.   &NBSP
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;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)  {            &nBsp System.out.println (E.getmessage ());         }    }         public static void getpersonbyprecondition (int  age,string neme) throws exception{         Preconditions.checknotnull (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);              }        public static  void checkstate (List<integer> intlist,int index) throws exception{         //-expressionTrue does not 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{         Preconditions.checkpositionindex (Index, intlist.size (),  "index " +index+ "  not in  list,  list size is: "+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  for  " + index+ "  Not in  list,  list size for: " +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.


Preconditions Elegant test parameters

Related Article

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.