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:
- Page request.
- Fetch object data from database.
- Create object.
- Return object to page.
And on POST or save:
- Get data from page.
- (Create object) could be done in 1.
- 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?