c.sokun
c.sokun

Reputation: 1662

Should constructor variables pass direct to private fields or properties?

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?

Upvotes: 3

Views: 620

Answers (5)

Romain Verdier
Romain Verdier

Reputation: 13011

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.

Upvotes: 1

Kev
Kev

Reputation: 119856

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

Upvotes: 2

Brian B.
Brian B.

Reputation: 1779

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).

Upvotes: 5

Adam Ness
Adam Ness

Reputation: 6283

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.

Upvotes: 3

Franci Penov
Franci Penov

Reputation: 76021

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

Upvotes: 3

Related Questions