1

From time to time I am facing with this issue and could not come up with final decision.

For example I have a User class. Is there any "recommended" way to create this object in database? For example;

User user = new User();
user.name = "John";
user.lastname = "Doe";
user.CreateNewUser();

vs

User user = new User();
user.name = "John";
user.lastname = "Doe";
User.CreateNewUser(user);

which one would be preferred way and why? Or does it depend on design pattern that project follows?

4

1 回答 1

1

经验法则:非静态方法应该基于(或修改)对象状态来工作。如果不是,它应该/可能是静态的。

从你的两个例子中,我更喜欢哪一个?答案都不是。

创建用户实体并存储它不是用户实体的操作,它是持久性的一部分。所以我可能会有类似的东西

User user = new User();
user.name = "John";
user.lastname = "Doe";
PersistenceManager.CreateNewUser(user);

注意 PersistenceManager 的静态方法,因为它不会以任何方式修改 PersistenceManager。

于 2013-07-05T23:20:53.957 回答