Skip to main content
typo in title corrected
Link
gnat
  • 20.5k
  • 29
  • 117
  • 310

Handla Handle object in handler or inside object

Source Link

Handla object in handler or inside object

I've start wondering what's the best practice when handling objects in web development.

Oversimplified the process when there is a page request often looks like:

  1. Page request.
  2. Fetch object data from database.
  3. Create object.
  4. Return object to page.

And on POST or save:

  1. Get data from page.
  2. (Create object) could be done in 1.
  3. Save object data to database.

I've written a sample code below:

public class Product
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Category { get; set; }

    public bool SaveNew()
    {
        SaveToDatabase(this.Id, this.Name, this.Category);
    }
    public void SetElementsById()
    {
         var datarows = GetProductDataByIdFromDB(this.Id);
         Name = datarows[1].ToString();
         Category = datarows[2].ToString();
    }
}

public class ProductHandler
{
    public bool SaveNew(Product product)
    {
        SaveToDatabase(product.Id, product.Name, product.Category);
    }
    public void GetProductById(int id)
    {
        Product product = new Product();
        product.Id = id;
        
        var datarows = GetProductDataByIdFromDB(id);
        product.Name = datarows[1].ToString();
        product.Category = datarows[2].ToString();
    }
} 

What is the best practice, to handle the object data within the object or in a handler type of class?