views:

27

answers:

4

Hey everyone,

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, UserIsRegisteredForActivity, 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.

A: 

sound like a class "User" with the properties/functions:
* ExistsInDatabase,
* IsRegisteredForActivity,
* GetIdFromFacebookId

Oops
+5  A: 

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
}
Darin Dimitrov
While I agree with Darin completely, I'd suggest that the reason you'd want to do this is so that the UserRepository can be mocked/substituted in your tests. Mocking/substituting classes with static methods is very difficult.
Colin Desmond
Excellent answer (again today) Darin. Cheers. Colin, thanks for the extra info. This will certainly make my unit testing much easier - Cheers!
Jamie Dixon
+1  A: 

I think we should avoid static methods as it will have issue in mocking. These methods are better suited for a UserRespository/UserService class.

Amitabh
A: 

Hey,

Either of those options are OK. Alternatively, you could define them as extension methods and attach them to the user class directly.

HTH.

Brian