dnagirl
dnagirl

Reputation: 20456

Method return values and exceptions

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)?

Upvotes: 1

Views: 146

Answers (5)

Lee
Lee

Reputation: 144136

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).

Upvotes: 1

Jonah
Jonah

Reputation: 10091

Exceptions are for errors on the part of the application or the server in my opinion. There's no point in returning a bogus date, and if you return false, it has to be checked every time.

The solution is to extend DateTime and create a Special Case (496), possibly called DateTimeNone.

Edit: changed answer to just special case

Upvotes: 1

Crozin
Crozin

Reputation: 44376

Return null instead of false. That's the most common and natural way. And yes, you'll have to check returned value every time.

Edit:

You could throw an exception but only if when() method cannot return DateTime due to some error or something.

Upvotes: 2

jasonbar
jasonbar

Reputation: 13461

Exceptions are for exceptional conditions. Trying to read from / act on a partially constructed object is fairly exceptional.

Does the code path make any sense at all if there is no timestamp available? Probably not?

Throw (and catch, as appropriate) an exception.

Upvotes: 1

drowe
drowe

Reputation: 2320

I'm a fan of returning false my self. It makes logical sense to me in an 'if' condition to simply state if($object->when() && $object->when()->before($otherdate)) etc, rather than returning a default date (like 12/31/1969, where that is a valid date).

Upvotes: 1

Related Questions