tags:

views:

187

answers:

2

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??

+2  A: 

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.

Otávio Décio
True, but some people say that a DTO should be set only once. Is it really a rule or just an opinion??
Perpetualcoder
I've never heard this. Do you have a URL?
John Saunders
@John - edited with the reference.
Otávio Décio
@Perpertualcode: rule? I wouldn't go that far. What I meant is that you don't need to define a constructor with all parameters to initialize. For me it would be a maintenance issue as well: if I add a new property I have to change the constructor.
Otávio Décio
@ocdecio = Does option 1 make it immutable?? some people like that stuff dont they like in F# or something? Just curious
Perpetualcoder
@Perpertualcode: no such thing, unless you want to declare the properties readonly.
Otávio Décio
+2  A: 

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.

Matt Brunell