Sarah Savage logo

A fusion of development and business

The danger of boolean flags in object methods

Developers like to use booleans as flags. They’re a convenient way to indicate something as on/off, true/false, yes/no. But the problem is that booleans are not clear from calling code exactly what they do. For example:


// Class definition
class MyClass
{
    public function setMyName(string $name, bool $saveInDatabase = true)
    {
        $this->name = $name;
        if ($saveInDatabase) {
            $this->saveName($name);
        }
    }
}

// Calling code
$myClass->setMyName('Sarah', false);

Does anyone in the calling scope have any idea what the defining scope is doing? Absolutely not.

The flag could be set for saving the name in the database, or for making it all capital letters, or for echoing the “Hello World!” option. We have no idea.

The solution

What I prefer to do in cases where a flag is a must-have, I use enums.

Consider the following code:


enum DatabaseSave
{
    case SAVE;
    case DONOTSAVE;
}

// Class definition
class MyClass
{
	private string $name;
    public function setMyName(string $name, DatabaseSave $saveInDatabase = DatabaseSave::SAVE)
    {
        $this->name = $name;
        if ($saveInDatabase === DatabaseSave::SAVE) {
            $this->saveName($name);
        }
    }
}

// Calling code
$myClass->setMyName('Sarah', DatabaseSave::DONOTSAVE);

This is MUCH clearer! We know that the second argument relates to DatabaseSave in the calling code, and that we are NOT saving it in the database.

What to know about enums

Enums (or enumerations) are a new feature as of PHP 8.1.0. You’ll need to upgrade in order to use the feature.

Enums typically don’t have a value unless they’re backed enumerations, in which case they can have valid scalar return types.

Enums can have methods (which you can define), and the backed enum has some methods defined on its interface like BackedEnum::from() and BackedEnum::tryFrom(). These are handy methods for getting an enum from a string (like that might be stored in a database).

Enums can be a tremendously useful tool in PHP, and they solve a number of issues. While they are not a replacement for constants, they are an opportunity for us to change the way we program for the better. Consider using enums instead of boolean flags where possible; it will make your code readable and your life easier.

2 thoughts on “The danger of boolean flags in object methods

  1. Yes, enums or named arguments. It would be nifty though if there was an attribute that would force developers to use named arguments. Like:
    $this->setMyName(‘Sarah’, false); // Error/warning
    $this->setMyName(firstName: ‘Sarah’, saveToDatabase: false); //OK

Thoughts? Leave a reply

Your email address will not be published. Required fields are marked *