Significance of POCO in C#

POCO stands for Plain old CLR objects. It is basically the .Net version of POJO (plain old java object).

The job of these objects are simple, they don’t care about what they are being used for and how. Such object also known as persistent ignorant objects.

These objects are being used to hold business state and logic.

The main benefits of POCO objects comes into play when we use things like Repository pattern, Façade pattern, ORM and dependency injection.

In simple words, you could create an ORM (let’s say entity framework) which pulls data from somewhere like web services or database etc., then project this data into objects(POCO).

These objects can be passed further down to app stack to service layer to web tier.

Then, if one day you decided to use different ORM model, then you should not touch the POCOs at all, the only thing should need to be change is the ORM.

Hence the term ‘persistence ignorant’ – they don’t care what they’re being used for or how they are being used.

So to sum up, the pros:

  • Allows a simple storage mechanism for data, simplifies serialization/passing around through layers
  • Goes hand in hand with dependency injection, repository pattern and ORMs. Flexibility.
  • Minimized complexity and dependencies on other layers. (higher layers only care about the POCOs, POCOs don’t care about anything). Loose coupling
  • Simple testability (no stubbing required for domain testing).

Some developers use Data Transfer Objects (DTOs) with the classes to pass the data between the layers because POCOs are also used to pass the data between the layers, but they become heavy. Hence they use DTOs, which are also the classes.

The main difference between DTO and POCO is that DTOs do not contain any methods. They only contain public members. Thus, sending the data, using a DTO is easy because they are lightweight objects.

Sample POCO class code:

public class Student {

public virtual int StudentID{get;set;}

public virtual string Name;

public virtual ICollection Subjects {get;set;}

}

Happy Coding!!!

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s