处理工厂类中的空异常 [英] handle null exception in factory class

查看:51
本文介绍了处理工厂类中的空异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在工厂类中处理空引用对象.例如,我的客户正在呼叫工厂通过接口创建对象的具体类,它将一个字符串作为参数传递以找到要实例化的合适的具体类.但是,如果不存在,它将返回null.我不希望客户端处理此异常.在工厂上课怎么办?

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?

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;
}

推荐答案

我不理解这种逻辑.如果客户有可能向工厂发送无效的请求,则必须有一种机制可以将其错误通知客户.

但是,您执行此操作后,客户端将始终必须在使用对象之前进行检查,无论是直接对返回的对象执行null检查还是对工厂设置的布尔值进行true/false验证.
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.


您实际上只有三个选择:

1)客户处理工厂退货.如果返回null,则客户端代码必须将其考虑在内.

2)引发异常.客户端不需要处理异常,这将导致程序崩溃.客户

3)返回一个实际上不做任何事情或具有某些默认行为的假人.可能比返回null更好.在某些情况下,可以返回默认值,例如零或空字符串.您可能可以对假人进行编程以执行一些有用的操作,例如将问题告知用户
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


这篇关于处理工厂类中的空异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆