0

Is it OK to use the constructor to set properties for a value object class or must I use dot notation and set each one, one-by-one?

I recently read an article that was saying I should do it one-by-one as value objects should only contain properties and went on to say using the constructor is not OK (best-practice wise).

Code:
("not OK")

var employee=new Employee(firstName,lastName,age);

("OK")

var employee=new Employee();
employee.firstName=firstName;
employee.lastName=lastName;
employee.age=age;

What's your take on this?

Thank you.

Francisc
  • 77,430
  • 63
  • 180
  • 276

1 Answers1

1

I've never heard anyone say that using a constructor to construct an object is a bad idea. The only case that I can think of is if the list of elements to be initialized can be changed (add/removed) and therefore changing the API of the object (which is bad, especially when developing libraries). In this case, I'd still use the constructor, but I'd pass in an initialization object (which contains n parameters) rather than modifying the function signature.

The statement "it's bad practice to use the constructor to construct the object" (paraphrasing) just doesn't make sense to me :P

Demian Brecht
  • 21,135
  • 5
  • 42
  • 46