Suppose I’m creating a session class, with relevant implementation as below:
public class Session()
{
private $id;
private $user;
}
The $user field contains an object of type User if the session is logged in, and is null if the session is not logged in to the site. The $id is the session id.
Suppose I now want to find out whether or not the user is logged in. Obviously I could check to see if $user is null, if it is then the user isn’t logged in – something like this:
public class Session()
{
private $id;
private $user;
public function isLoggedIn()
{
return !is_null($user);
}
}
Alternatively, I could store a boolean session variable, $loggedIn or something, set to false on log in and otherwise initialised in the constructor to be false to test against instead:
public class Session()
{
private $id;
private $user;
private $loggedIn;
public function isLoggedIn()
{
return $loggedIn;
}
}
Would one approach produce better performance than the other here? If so, which, and why? Alternatively, is one approach preferable to the other for any reason unrelated to performance?
Simpler is better. If you introduce a new variable to track whether or not $user is null, then you also introduce the possibility that is_null($user) and $loggedIn don’t match. Avoiding the hassle of having to worry about that is worth much more than any possible micro-optimization you may gain in performance.