Search code examples
phpdatetimereturn-valuereturn-type

Best Practice : Seconds Since datetime when datetime is empty or null


I feel this question is language agnostic, but I will use PHP for my example


abstract class myUserClass {
  private $last_visit = null;

  abstract getLastVisit() ?string;
  abstract secondsSinceLastVisit() int;

}

Lets say you have some datetime (like a last_visit) property on an object

last_visit = 2020-10-10 09:25:25

last_visit can be a string representation of the datetime OR null of user has never visited

And then you have a method like secondsSinceLastVisit() : int

And this function returns an int representing the number of seconds SINCE last_visit

What would be the best practice for returning when last_visit is null?

We could: return null which means this is undefined Return some_really_large_number meaning - a long time ago Something else???

I ran into trouble doing this


if( !$user->secondsSinceLastVisit() )
{
 //user has never visited
}

This failed during some unit testing when secondsSinceLastVisit() returned zero! 0

So, I changed by test to is_null( $user->secondsSinceLastVisit() ) which solves this problem

My question is general in nature - What is a good practice here for the return value of secondsSinceLastVisit() when last_visit is null?


Solution

  • There's really 2 good options:

    1. Return null. null is often a stand-in for the absence of a value, so this makes perfect sense here.
    2. Throw an Exception

    I think either is fine, but which one you choose depends on the answer to the question:

    "Is it a bug when somebody calls secondsSinceLastVisit() for a user when the user has not visited yet?"