Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should I put validation logic in a POCO?

Let's say I have a POCO like so:

public class Name
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

FirstName and LastName cannot be null. Should I add in a method like this:

public List<Error> Validate()
{
    var errors = new List<Error>();

    if (String.IsNullOrEmpty(FirstName))
        errors.Add(new Error("FirstName", "You must fill out first name."));
    if (String.IsNullOrEmpty(LastName))
        errors.Add(new Error("LastName", "You must fill out last name."));
}

where Error is a struct that contains a NameValueDictionary. Is this a good way of doing things? I can potentially see a problem with the repository where someone attempts to save this POCO without running it through Validate() first.

like image 659
Daniel T. Avatar asked Sep 25 '09 22:09

Daniel T.


People also ask

How to perform validation in c#?

Step 1: Create a Windows form application. Step 2: Choose “ErrorProvider” form toolbox. Step 3: Select the Text box and go to its properties. In properties choose “Events” and under focus double click on “validating”.

What is Poco in C#?

POCO Entities (Plain Old CLR Object) A POCO entity is a class that doesn't depend on any framework-specific base class. It is like any other normal . NET CLR class, which is why it is called "Plain Old CLR Objects".


1 Answers

I wouldn't. My POCO's tend to have different validation based on their context. "My Person objects have to have an address in this application, but they only have to have a phone number in this other application"... is the sort of thing you want to keep an eye on and be flexible for.

I'm an advocate of the anemic domain model as I typically reuse the same domain, but assign different behavior and validation based on the context (which could even be different areas of the same application).

When implementing new functionality, I typically look at my class and ask myself this question: does this seem like the responsibility of this class, or would it be more suitable for a class with a different set of responsibilities? We call this checking for "Feature Envy" and it effectively helps to separate out what the class is and is not concerned about.

like image 153
Travis Heseman Avatar answered Oct 14 '22 18:10

Travis Heseman