Parameter validation under Java and C #

Source: Internet
Author: User
Tags custom name

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 #

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.