C# – Benefits of Having Pure POCO Models

cnetpoco

What is the major benefit of having pure POCO models? I get that Models should be clean and simple, but I tend to like to keep the maintenance of child objects within the model classes. For example if I have a ClassA and ClassB defined as follows:

public class ClassA
{
    public string MyProp { get; set; }
    public IEnumerable<ClassB> Children { get; }

    public void AddChild(ClassB newChild) { /*... */ }
    public void RemoveChild(ClassB child) { /* ... */ }
}

public class ClassB
{
    public string SomeProp { get; set; }
} 

Is there something inherently wrong with having the add and remove methods? Should I instead just expose the list and allow client code to add whatever passing the responsibility of simple data validations like not null, and not duplicate on to another class?

Any help is appreciated.Thanks.

Best Answer

Your two questions are unrelated.

What is the benefit to having pure POCO models?

A pure POCO is not dependent on some enterprisy framework, convention, [] thingy, or intimately connected to some object that is similarly dependent. In other words, the world can completely change around a POCO and it just keeps on doing what it does without caring. You can't break it by updating a framework, by moving it into a new system, or looking at it funny. It just keeps working. The only dependencies are the things it explicitly asks for.

POCO is nothing more than the POJO idea. The J was changed to a C because people look at you funny when you explain a concept that has Java in its name if those people are using C#. The idea is not dependent on language. They could have simply called it Plain Old Objects. But who wants to brag about using POO?

I'll let Fowler explain the origins:

The term was coined while Rebecca Parsons, Josh MacKenzie and I were preparing for a talk at a conference in September 2000. In the talk we were pointing out the many benefits of encoding business logic into regular java objects rather than using Entity Beans. We wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely.

martinfowler.com : POJO

As for your other question:

Is there something inherently wrong with having the add and remove methods?

I don't like A directly knowing about B. But that's a DIP thing not a POJO thing.