MVC, I understood it, but separating the model for the filing functions and perhaps even the business logic and hellip; Best practice?

advertisements

C# ASP .NET MVC 4.0

I understand the MVC pattern, but when it comes down to the model:

public class User
{
    int id { get; set }
    int name { get; set; }
}

I could see a benefit to dividing the business logic from the repository ( data fetchers ). Something like:

public class UserRepository
{
    IEnumerableList<User> GetAllUsers()
    {
        IEnumerableList<Product> users = //LINQ or entity;
        return IEnumerableList<Product> users;
    }  

    int GetScoreByUserId( id )
    {
        int score = //LINQ or entity;
        return score;
    }
}

Would the business logic go into the User class like:

public class User
{
    public int id { get; set }
    public int name { get; set; }

    public bool HasDiscount( int id )
    {
        if( GetScoreByUserId( id ) > 5 )
            return true;
        return false;
    }
}

Does anyone have a decent example. It's not as easy as 1 2 3 to find such an explicit example for me.

Does the above code seem okay? Should the Repository extend the User or should it be a separate class.. or should all of this stuff just go in the User class itself?

EDIT::---- So something like this?

public class UserBusinessLogic
{
    public bool HasDiscount( int id )
    {
        if( GetScoreByUserId( id ) > 5 )
            return true;
    }
}

EDIT::---- Clarification of how I understand this now


There are a few options in your situation. They are described in, for example, such book as "Patterns of Enterprise Application Architecture" by Martin Fowler. So it depends on the architecture pattern that you are going to choose.

When you were trying to find a solution you actually make smth like domain model pattern (User class for related business logic and separate UserRepository class for data access).

You can also merge these responsibilities in one class User (both business logic and data access) and so you will come to Active Record pattern.

However each pattern has its own pros and cons, I think that it definitely would be better to use domain model as it leads to OOP and right separation of concerns.