C# add validation on a setter method

前端 未结 5 1145
花落未央
花落未央 2020-12-03 05:58

I have a a couple of variables that i define in C# by:

public String firstName { get; set; }
public String lastName { get; set; }
public String organization          


        
5条回答
  •  情深已故
    2020-12-03 06:33

    If you want to validate when the property is set, you need to use non-auto properties (i.e., manually defined get and set methods).

    But another way to validate is to have the validation logic separate from the domain object.

    class Customer {
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Organization { get; set; }
    }
    
    interface IValidator {
        bool Validate(T t);
    }
    
    class CustomerValidator : IValidator {
        public bool Validate(Customer t) {
            // validation logic
        }
    }
    

    Then, you could say:

    Customer customer = // populate customer
    var validator = new CustomerValidator();
    if(!validator.Validate(customer)) {
        // head splode
    }
    

    This is the approach I prefer:

    1. A Customer should not responsible for validating its own data, that is another responsibility and therefore should live elsewhere.
    2. Different situations call for different validation logic for the same domain object.

提交回复
热议问题