方法返回值和异常 [英] Method return values and exceptions

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

问题描述

我有一个名为 iIncident 的界面,它定义了一个方法 when() when()应该返回一个 DateTime 对象。如果 $ object-> when()没有 DateTime 返回为可能是在实例化对象之后并在其所有属性设置之前的情况。



我的选择是:



<
  • return false

  • 抛出某种异常

  • 返回一些默认值 DateTime 像'9999-01-01'

  • 我的由于 $ object 真的不能作为事件发生,直到知道发生的时候才会有一个异常 。我不想返回一个默认的 DateTime ,因为它比较复杂,而不是真的。而且我真的不想返回false,因为我每次调用该方法时都必须检查它 - 但是如果这是首选方法,我想我会。



    是否抛出异常最好的方法?有没有一个我应该使用的预定义的异常类型(没有一个SPL的人把我当成特别合适的 - 但这可能表示我缺乏经验)?

    解决方案

    我认为问题是您允许在不一致的状态下创建对象。如果对象应该能够创建日期值,那么它应该在其构造函数中而不是通过属性接收它所需要的所有依赖关系。如果这不可能,那么你应该考虑试图通过工厂(或工厂方法)封装施工过程。


    I have an interface called iIncident which defines a single method when(). when() should return a DateTime object. I'm trying to decide what to do if $object->when() has no DateTime to return as might be the case just after an object is instantiated and before all its properties are set.

    My choices are:

    1. return false
    2. throw some kind of Exception
    3. return some default DateTime like '9999-01-01'

    My inclination is to go with an Exception since $object really can't act as an incident until it knows when it occurred. I don't want to return a default DateTime because it complicates comparisons and it's not true. And I don't really want to return false because then I have to check for it every time I call the method- but if that is the preferred method, I guess I will.

    Is throwing an exception the best way? And is there a predefined exception type I should use (none of the SPL ones struck me as particularly appropriate- but that might just indicate my lack of experience)?

    解决方案

    I think the problem is that you're allowing an object to be created in an inconsistent state. If the object should be able to create date values, then it should receive all the dependencies it needs to do so in its constructor instead of through properties. If this is not possible, then you should consider trying to encapsulate the construction process through a factory (or factory method).

    这篇关于方法返回值和异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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