Does it make sense to have a model with only static methods?
I have an ASP.NET MVC 2 project that I'm working on and I'm wondering where I should place some of my code.
I currently have a UsersModel which consists of a bunch of static methods that operate against my data context.
These methods include such things as: UserExistsInDatabase
, U开发者_运维技巧serIsRegisteredForActivity
, GetUserIdFromFacebookId
etc etc.
Should these methods be inside a UsersModel class or would they be more suited to a user helper class outside of the models context?
Cheers for any pointers.
Don't use static methods. Abstract them in a repository:
public interface IUsersRepository
{
bool UserExistsInDatabase(User user);
bool UserIsRegisteredForActivity(User user);
...
}
then implement against some data store:
public class UsersRepository : IUsersRepository
{
...
}
and finally give your controller an instance of this repository so that it can work with users:
public class HomeController : Controller
{
private readonly IUsersRepository _repository;
public HomeController(IUsersRepository repository)
{
// the repository is injected into the controller by the DI framework
_repository = repository;
}
// ... some action methods that will use the repository
}
I think we should avoid static methods as it will have issue in mocking. These methods are better suited for a UserRespository/UserService class.
sound like a class "User" with the properties/functions:
* ExistsInDatabase,
* IsRegisteredForActivity,
* GetIdFromFacebookId
Either of those options are OK. Alternatively, you could define them as extension methods and attach them to the user class directly.
HTH.
精彩评论