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.

4

1 に答える 1

1

コンストラクターを使用してオブジェクトを構築するのは悪い考えだと言う人を聞いたことがありません。私が考えることができる唯一のケースは、初期化する要素のリストを変更 (追加/削除) できる場合であり、したがってオブジェクトの API を変更することです (これ、特にライブラリを開発する場合に悪いことです)。この場合、引き続きnコンストラクターを使用しますが、関数シグネチャを変更するのではなく、初期化オブジェクト (パラメーターを含む) を渡します。

「コンストラクターを使用してオブジェクトを構築するのは悪い習慣です」というステートメント(言い換え)は、私には意味がありません:P

于 2011-05-09T22:57:57.233 に答える