C# – Method to validate an object – should I have one method encapsulating all validation logic

csolidunit testing

I have a class, Customer which has some basic properties on it such as firstname, surname, email, dateofbirth. I have written another class called CustomerValidation which currently has one public method and three private methods. The public method is:

public bool ValidateCustomer(Customer customer)

This method calls three private methods which validate the name, email address and date of birth of the customer passed in, returning true only if all of these methods themselves return true.

However, even though it makes sense to me to validate a customer in one call, another part of me is thinking, if I unit test this, I could pass in a Customer with multiple invalid fields and not actually know if each private method is working correctly, as just one of these methods returning false would give me a potentially false positive.

It doesn't make sense to me to write tests to the public API that target the implementation detail. So I'm wondering whether I should make all the methods public, which still doesn't feel right or refactor the methods out into their own classes and rework my validation logic.

Best Answer

Instead of bool you could return some integer error code or even validation message in string. This would provide you a knowledge of what failed the validation. The string solution have also particular advantage because you already have composed message to inform end user about results of validation.

Related Topic