The input and validation of parameters is often encountered during development, and the general verification method is as follows:
Public BOOLRegister (stringNameintAge ) { if(string. IsNullOrEmpty (name)) {Throw NewArgumentException ("name should not being empty","name"); } if(Age <Ten|| Age > -) { Throw NewArgumentException ("The age must between"," Age"); } //...}
In doing so when the demand changes, the code to change the corresponding more, this is more troublesome, recently exposed to Java and C # 2 kinds of convenient parameter verification method, simple introduction.
Java Parameter Validation:
Use an auxiliary class under Google's guava:
import com.google.common.base.Preconditions;
Example code:
Public Static voidCheckpersoninfo (intAge , String name) {preconditions.checknotnull (name,"Name is null"); Preconditions.checkargument (Name.length ()> 0, "name is longer than 0"); Preconditions.checkargument ( Age> 0, "Age must be greater than 0"); System.out.println (' A person Age: ' + age + ', Name: ' +name); } Public Static voidGetpostcode (String code) {preconditions.checkargument (Checkpostcode (code),"ZIP code does not meet the requirements"); SYSTEM.OUT.PRINTLN (code); } Public Static voidMain (string[] args) {Try{checkpersoninfo (Ten, "FDSFSD"); Checkpersoninfo (10,NULL); Checkpersoninfo (-10, "FDSFSD"); Getpostcode ("012234"); } Catch(Exception e) {e.printstacktrace (); } }
When the parameter does not satisfy the request, throws the exception information, the exception carries the information to be later the custom string, this writes is more convenient.
C # Parameter Validation:
Use fluentvalidation this class library, the reference address is below.
How to use:
A simple Person class:
Publicclass person { publicstringsetget ; } Public int Set Get ; } Public Person (stringint age ) { = name; = Age ; } }
Validation class for Person:
Public classPersonvalidator:abstractvalidator<person> { PublicPersonvalidator () {rulefor (x= X.name). Notempty (). Withmessage ("the name cannot be empty"); Rulefor (x= X.name). Length (1, -). Withmessage ("Last name character cannot exceed"); Rulefor (x= X.age). GreaterThan (0). Withmessage ("age must be greater than 0"); } Private BOOLValidname (stringname) { //Custom name validating logic goes here return true; } }
Use:
classProgram {Static voidMain (string[] args) {Person Customer=NewPerson (NULL,-Ten); Personvalidator Validator=NewPersonvalidator (); Validationresult Results=Validator. Validate (customer); BOOLvalidationsucceeded =results. IsValid; IList<ValidationFailure> failures =results. Errors; foreach(varFailureinchfailures) {Console.WriteLine (failure). ErrorMessage); } console.readkey (); } }
Fluentvalidation documentation for use: http://fluentvalidation.codeplex.com/documentation
Resources:
http://fluentvalidation.codeplex.com/
Https://github.com/JeremySkinner/FluentValidation
Parameter validation under Java and C #