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:
- return false
- throw some kind of
Exception - return some default
DateTimelike ‘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).