Question

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?

Was it helpful?

Solution

Rule of thumb: A non-static method should work based on (or modify) the objects state. If it does not, it should/could be static.

From your two examples, which one would I prefer? The answer is neither.

Creating a user entity and storing it is not an operation of the user entity, it is part of the persistence. So what I probably would have is something like

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

Note the static method of the PersistenceManager, as that one does not modify the PersistenceManager in any way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top