Create an Object Without a Constructor

Do you ever get into a situation where a constructor just does not seem like the best way to create your object? Maybe you are using the constructor with the id of the object as the parameter, then creating the object from the results from the database. I will use a very simple House object as an example:

    public class House
    {
        public int HouseID { get; set; }
        public Address HouseAddress { get; set; }

        public House(int id)
        {
            this.HouseID = id;
            this.HouseAddress = //get data from database
        }

What happens when there is nothing found in the database? A constructor cannot return null. What happens when you want to also get the house by the owner ID, which is also an int. This will cause two methods with the same signature. The second one maybe a bad example, but you get the idea.

In any case, using a constructor for actions like this can be limiting, confusing, and just bad design. An alternative approach is to take a bit from the factory pattern. Instead of using a constructor, we can create a static method on our class to return the object. This gives us more flexibility, and also the ability to return a null object. So, instead of the above, we can do this:

    public class House
    {
        public int HouseID { get; set; }
        public Address HouseAddress { get; set; }

        private House() {}

        public static House GetHouseByID(int id)
        {
            //Get house by the ID
        }

        public static House GetHouseByOwner(int ownerID)
        {
            //Get house by the owner id
        }

Beyond allowing us to return a null, you will notice that I named these methods according to what they are actually doing. This is another benefit so you don’t have to purely rely on comments to know how you are getting the object.

Yes, the title may be a little misleading because a constructor will be used, just not a public constructor.

More