Reputation: 2681
Pretty simple question, say I have a class with 20 reference type properties that I know will only be set at class creation/immediately after class is created and where none of the properties are really mandatory.
In this scenario, would best practice be to create a ctor
accepting 20 properties (which, since they are all reference types, would still allow you to pass null
if you wanted to) and to ensure none of my properties have a setter
or ...
To simply not have a ctor
at all and just provide a setter
for all of my properties?
I am leaning towards the latter because of ease of implementation and (arguably) cleaner code even though that doesn't guarantee object immutability, but again these classes are only used internally and I know that I won't be changing them anyway.
EDIT
If you're going to vote to close the question, at least have the decency of explaining why you think the question is not "good enough" for the ohh-so-high SO standards.
If this is not a question that belongs here, I really don't know what SO is for anymore.
Upvotes: 0
Views: 75
Reputation: 3231
You should make them properties and use an object initializer:
class Cat
{
// Auto-implemented properties.
public int Age { get; set; }
public string Name { get; set; }
public object OtherProperty { get; set; }
}
Cat cat = new Cat { Age = 10, Name = "Fluffy" };
This gives you nice compact code, without having to specify the properties you don't need. Even if you do specify all the properties, it's not much longer.
I'd use a constructor where properties are mandatory, or based on some sort of source object like a DataRow or file.
Upvotes: 0
Reputation: 1
It looks like Single Responsibility Principle violation. It's recommended to have 0-3 parameters in method including constructor.
Upvotes: -1
Reputation: 460238
If all these properties aren't mandatory and they don't have to be readonly, you don't need a constructor. No one wants to call a constructor that takes 20 arguments, especially if they aren't necessary.
So even if this question tends to be subjective, use properties and omit the constructor.
Upvotes: 3