I want to be able to instantiate any object in my application with this kind of code:
SmartForm smartForm = SmartForm.Create("id = 23");
Customer customer = Customer.Create("id = 222");
I'm now debating what Create() should return if that object does not exist.
if Create() returns an empty object, then this is kind of a "null pattern" and I can still pass that object around my application and call methods on it, which makes programming with this model convenient and easy
if Create() returns null, then I need to check after every instantiation if the object equals null or not, which makes programming a bit more tedious but more explicit. A problem with this is that if you forget to check the null, your application could work for a long time without you knowing that you're not checking null, then break all of a sudden
if Create() throws an exception, it is basically the same as returning null but makes programming even more tedious by making you create a try, next, finally block for each instantiation, but you could throw various types of exceptions (which you can't with the null solution) which could bubble up so that you could more explicitly handle the deep errors on your UI, so this I would think is the most robust solution although would produce try/catch code bloat
So it seems to be a lightness/robustness trade off. Does anyone have any experience of making a decision along these lines where you experienced advantages or disadvantages because of that decision?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TestFactory234.Models
{
public class SmartForm : Item
{
public string IdCode { get; set; }
public string Title { get; set; }
public string Description { get; set; }
public int LabelWidth { get; set; }
public SmartForm() { }
private SmartForm(string loadCode)
{
_loadCode = loadCode;
TryToInstantiateFromDatabase();
}
public static SmartForm Create(string loadCode)
{
SmartForm smartForm = new SmartForm(loadCode);
if (!smartForm.IsEmpty())
{
return smartForm;
}
else
{
return null;
}
}
}
}