1.2.63. Avoid Optional Properties

Avoid optional properties, to prevent littering the code with existence checks.

When a property has to be checked once for existence, it is safer to check it each time. This leads to a decrease in readability and a lot of checks added to the code.

Either make sure the property is set with an actual object rather than with null, or use a null object. A null object offers the same interface than the expected object, but does nothing. It allows calling its methods, without running into a Fatal error, nor testing it.

<?php

// Example is courtesy 'The Coding Machine' : it has been adapted from its original form. See link below.

class MyMailer {
    private $logger;

    public function __construct(LoggerInterface $logger = null) {
        $this->logger = $logger;
    }

    private function sendMail(Mail $mail) {
        // Since $this->logger may be null, it must be tested anytime it is used.
        if ($this->logger) {
            $this->logger->info('Mail successfully sent.');
        }
    }
}

?>

See also Avoid optional services as much as possible, The Null Object Pattern – Polymorphism in Domain Models and Practical PHP Refactoring: Introduce Null Object.

1.2.63.1. Suggestions

  • Use a null object to fill any missing value

  • Make sure the property is set at constructor time

1.2.63.2. Specs

Short name

Classes/AvoidOptionalProperties

Rulesets

All, Analyze

Exakat since

0.12.0

PHP Version

All

Severity

Major

Time To Fix

Slow (1 hour)

Precision

Very high

Features

property, null

Examples

ChurchCRM, Dolibarr

Available in

Entreprise Edition, Exakat Cloud