Perpetualcoder
Perpetualcoder

Reputation: 13571

What is the best practice when implementing a data transfer object or POCO ? How should your POCOs look like?

Which of the following is the best way to implement a poco?

Option 1:

public class PocoOption1
{
  public PocoOption1(int val1,string val2)
  {
    Val1=val1; Val2=val2;
  }

  public int Val1{get;private set;}
  public int Val2{get;private set;}
}

Option 2:

public class PocoOption2
{           
  public int Val1{get;set;}
  public int Val2{get;set;}
}

What are the potential pro-cons of each approach?? Does it matter? Some people say that a DTO should be set only once. Is it a rule or just an opinion??

Upvotes: 3

Views: 1804

Answers (2)

Otávio Décio
Otávio Décio

Reputation: 74270

With the new C# syntax where you can do things like:

Customer customer =  new Customer{ Id = 1, 
     Name="Dave",                                             
     City = "Sarasota" };

you can safely use Option 2.

Please check here.

Upvotes: 3

Matt Brunell
Matt Brunell

Reputation: 10389

The options are slightly different. Option 1 allows you to set Val1, Val2 only once. Option 2 allows you to set and reset those values.

In general I am a fan of public default constructors. It makes the API more easily consumed. This is discussed in some detail by Krzysztof Cwalina and Brad Abrams in the Framework Design Guidelines book. Here are the highlights:

  • Use the 'Create, Set, Call' pattern. Have a default constructor with no parameters. Then allow properties to be set on the object (in any order). Then allow methods to be called.
  • A default constructor is the canonical method of object construction. This will be the first option the user tries.
  • Forcing a user to choose parameters at construction time may be difficult. Also, some parameters may be optional.
  • Let your object be in an invalid state for a limited period of time. Throw exceptions to communicate API misuse. (If an object has two dependencies then throw InvalidOperationException if the user tries to call a method without the necessary settings.)

In my opinion, Option 2 is the way to go.

Upvotes: 3

Related Questions