Boolean vs Null – Is a New Boolean Field Better Than a Null Reference?

booleannull

For example, suppose I have a class, Member, which has a lastChangePasswordTime:

class Member{
  .
  .
  .
  constructor(){
    this.lastChangePasswordTime=null,
  }
}

whose lastChangePasswordTime can be meaningful absent, because some members may never change their passwords.

But according to If nulls are evil, what should be used when a value can be meaningfully absent? and https://softwareengineering.stackexchange.com/a/12836/248528, I shouldn't use null to represent a meaningfully absent value. So I try to add a Boolean flag:

class Member{
  .
  .
  .
  constructor(){
    this.isPasswordChanged=false,
    this.lastChangePasswordTime=null,
  }
}

But I think it is quite obsolete because:

  1. When isPasswordChanged is false, lastChangePasswordTime must be null, and checking lastChangePasswordTime==null is almost identical to checking isPasswordChanged is false, so I prefer check lastChangePasswordTime==null directly

  2. When changing the logic here, I may forget to update both fields.

Note: when a user changes passwords, I would record the time like this:

this.lastChangePasswordTime=Date.now();

Is the additional Boolean field better than a null reference here?

Best Answer

I don't see why, if you have a meaningfully absent value, null should not be used if you are deliberate and careful about it.

If your goal is to surround the nullable value to prevent accidentally referencing it, I would suggest creating the isPasswordChanged value as a function or property that returns the result of a null check, for example:

class Member {
    DateTime lastChangePasswordTime = null;
    bool isPasswordChanged() { return lastChangePasswordTime != null; }

}

In my opinion, doing it this way:

  • Gives better code readability than a null-check would, which might lose context.
  • Removes the need for you having to actually worry about maintaining the isPasswordChanged value that you mention.

The way that you persist the data (presumably in a database) would be responsible for ensuring that the nulls are preserved.