skip to Main Content

I recently saw a project that uses null as a default value on class properties, specifically entities.

For example

class SomeEntity
{
    private ?int $id = null;

    public function getId(): ?int
    {
        return $this->id;
    }

    public function setId(int $id): void
    {
        $this->id = $id;
    }
}

Notice that the setter setId(int $id) does not allow null values.

Is there any particular advantage to having this setup? Why not have no value properties? I can’t think of any benefits(or drawbacks for that matter) to having default null or no default.

3

Answers


  1. This is a new trend – making default behavior more obvious. You can ignore it if it’s already obvious to you.

    Login or Signup to reply.
  2. It will produce an error if you access the property that don’t have a default value when its not initialized.

    class Entity
    {
        protected int $id;
    
        //getter and setter function
    }
    
    $entity = new Entity;
    $entity->getId(); // It will produce an error since your getting a value that is not yet initialized
    
    
    class Entity
    {
        protected ?int $id = null;
     
        //setter and getter
    }
    
    $entity = new Entity;
    $entity->getId(): // it will return null
    

    Let’s say you want to override the value of property depending on its current value.

    $entity = new Entity;
    
    if (is_null($entity->getId())) {
      $entity->setId(000123);
    }
    

    If we use the getId() without the default value of null it will produce an error.

    Login or Signup to reply.
  3. As it said; setId(int $id) not allowing null values, because this enforces rule that ID must always be an integer and never null. This can be important for maintaining data integrity, especially in systems where the ID is used as a unique identifier for the entity.

    In contrast, not providing a default value means that the property is uninitialized until it’s explicitly set. This can lead to issues if the property is accessed before being set, potentially resulting in errors or warnings about accessing uninitialized properties. So, whether to use null as a default value or not, depends on the specific requirements of your application and how you want to handle the absence of a value, Both approaches have their merits and potential drawbacks, and the best choice depends on the context in which they are used.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search