Home > database >  Is it bad to have methods in a model?
Is it bad to have methods in a model?

Time:03-01

In ASP.NET MVC I'm thinking to implement a method that converts data to JSON. However, I'm not sure where to add this method. Should I add it in Controller, service class, or Model? So, for example, let's say I have a model named book and a controller named Library.

public class Book
{
    public string Name { get; set; }
    public string Json { get; set; }
}

public class Library: Controller
{
    public ActionResult Book(string bookName)
    {
        return View();
    }
}

Should I add a private method like JsonConverter(object jsonToConvert) in Book class and call it in the constructor of Book? So, a user will pass an object to be converted to Book class, and then when instantiated it will be converted to Json and assigned to Book.Json.

Is adding methods in a model a bad practice? Is it better to add a service class that has JsonConverter and do the conversion in the controller?

So, like

public class Library: Controller
{
    public ActionResult Book(string bookName)
    {
        var book = GetBook(bookName)
        var json = Service.ConvertJson(book.object)
        return View(book, json);
    }
}

To sum up my question: is it bad practice to add private methods in a model and manipulate data format? The reason why I don't want to do the conversion in the controller is that I think it is a bad practice to convert data format in a class as the data layer is Model. Am I wrong?

CodePudding user response:

The idea is to keep layers abstract from each other, and keep in mind Single-Responsibility principle, a class should do one thing, and one thing well.

In that regard, your model is responsible for defining the data schema. An instance of a model would hold the data. And that's it.

So this is your model

public class Book
{
  public string Name {get; set;}
  public string Json {get; set;}
}

In this case outputting an instance of a Book is an endpoint concern. It's not related to your business logic which concerns your services.

So keeping it in the controller like

public class Library: Controller
{
  public ActionResult Book(string bookName)
  {
    var book = GetBook(bookName)
    var json = Service.ConvertJson(book.object)
    return View(book, json);
  }
}

is what you can do best.

Whenever you are trying to achieve something ask yourself: Whose responsibility should this be?

  • Controller: Think of this like the waiter who greets you, shows you to your table and gets your order in a restaurant.
  • Service: This is the chef who cooks your meal.
  • Model: This is the meal you are going to order in the menu.

Converting to JSON is related to serving, so this responsibility goes to the controller.

  • Related