Click here to Skip to main content
15,878,852 members
Please Sign up or sign in to vote.
2.50/5 (2 votes)
See more:
How do I handle a null reference object within the factory class. For example, my client is calling the factory to create concrete classes of objects via an interface.It passes a string as an argument to find the appropriate concrete class to instantiate. But if it does not exist it will return null. I don't want the client to handle this exception. How would I do it in the factory class?
C#
Interface theObject =theFactory.GetObject("Some string that does not exist");
public static Interface CreateConcreteClass(string eulaVariant)
{
   Interface eulaObj;
   if (eulaVariant == "File one Exists")
   {
        Obj = new ClassA();
        return eulaObj;
   }
   if (eulaVariant == "File two exists&")
   {
        Obj = new ClassB();
        return Obj;
   }
   return null;
}
Posted
Updated 12-May-12 7:10am
v4

I don't understand the logic of this. If there is a possibility that the client can send an invalid request to the factory then there must be a mechanism to inform the client of their mistake.

However you do it the client will always have to check something before using the object, be it a null check directly on the returned object or true/false on boolean value set by the factory.
ISomething obj = factory.Create("someobject");
if (obj == null) {
  // No!
} else {
  // OK to use
}

ISomething obj;
if (factory.Create(out obj)) {
  // ok to use


Alan.
 
Share this answer
 
You really only have three options:

1) the client deals with null returning from the factory. If a null is returned, then the client's code must take that into account.

2) an exception is raised. The client does not need to handle the exception, which will cause the program the crash. The client

3) Return a dummy that really does nothing, or has some default behaviour. Maybe better than returning a null. In some cases a default value can be returned, like zero or empty string. You can possibly program the dummy to do something useful, like informing the user of the problem
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900