Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

properties - C# add validation on a setter method

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 { get; set; }

What i want is to add validation to these methods when you try to set a value. Lets say your going to set a value for firstName, the i should pass thrue a regexp to actuelly be set, otherwise an exception should be thrown. Is this possible to build with this "short syntax" or should I go for standard (like in JAVA) getters and setters and in there validate the data?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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<T> {
    bool Validate(T t);
}

class CustomerValidator : IValidator<Customer> {
    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.

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...