views:

362

answers:

5

Now this is .NET but I am sure the principal should apply to all OOP language, to simplify I take .NET as an example:

R# usually creator constructor and passing incoming variable to private field, which for me mi tend to pass it to Property.

Any opinion on how the different and what is the best practice for that?

+2  A: 

Passing the parameter through the property setter allows you to keep any validation code in one place only.

Franci Penov
+2  A: 

I would recommend sending it to the Property, rather than directly to the private field, though your actual implementation would dictate the exact conditions. For example, sometimes there are events fired when you use the Property, and you don't want to fire those events during the constructor. Or perhaps you want to circumvent the Property logic for some other reason.

Adam N
+5  A: 

Using properties is OK as long as they are not virtual/overridden. Properties are essentially methods, and you should not call virtual methods from within the constructor because the appropriate type may not be constructed yet. Microsoft has listed their own set of guidelines, just scroll down to the bottom to see the relevant guidance and code snippet illustrating the problem (they illustrate it using methods, but as I mentioned .NET properties are essentially special methods).

Brian B.
+2  A: 

Be careful using the Property Setter. You may have code in the setter which can cause unexpected side effects.

Kev
+1  A: 

I manipulate fields inside the constructor. Fields really represent the inherent state of your object, and the constructor job is to initialize this internal state. Properties are just here for encapsulation purpose, and are a part of the public interface to the object state.

The transformation logic you apply to the constructor arguments or to the properties input values before setting the internal state of the object could be very different. Anyway, if it is the case, I used to use an explicit transformation method called from the property setter and from the constructor, instead of directly chaining constructor on the property setter.

If there is no logic at all, I can't see why you would like to use property setter inside constructor.

Romain Verdier