What is the default Null Object?

9

I asked this question in SOEN,

asked by anonymous 24.09.2015 / 16:12

1 answer

6

It is an object that is created to simulate another object with the same contracts, but without any functionality. No state and no real behavior. Both types are compatible with each other because they serve the same contract, implement the same interfaces, and possibly extend the same type.

This is a way to avoid using the null state of objects that most languages use. When there really is a semantic need, a situation where an object of a type is null, you use this object that serves the same contracts but does nothing.

This form tends to be "more object oriented" by providing a better abstraction for a situation of unknown value, avoiding side effects, and facilitating coding that does not need to treat specific cases as an exception to the rule.

There is a bit of controversy about its use since it may also end up hiding some programming errors that would be caught if it used a null value, which would be a completely different and incompatible type.

The criticism occurs because although it is fulfilling the contract, it does something unexpected. And you see, there are people who criticize other features like operator overloading because someone can subtract from the addition operator. In this case it is certain that the method does something different than expected. Finding logic error is much harder than finding programming error. And this pattern induces logic error. This is why it is rare to see it being used. And rarer still compendiums of design patterns quoting it.

Improving the OS response example:

 
interface IAnimal {
    public function makeSound();
}

class Dog implements IAnimal {
    public function makeSound() { 
        echo "Woof.."; 
    }
}

class Cat implements IAnimal {
    public function makeSound() { 
        echo "Meowww.."; 
    }
}

class NullAnimal implements IAnimal {
    public function makeSound() { 
        // silence...
    }
}

$animalType = 'elephant';
switch($animalType) {
    case 'dog':
        $animal = new Dog();
        break;
    case 'cat':
        $animal = new Cat();
        break;
    default:
        $animal = new NullAnimal();
        break;
}
$animal->makeSound(); // ..the null animal makes no sound

function Exemplo(IAnimal $animal) {
    $animal->makeSound();
}

There are cases where you need to treat the condition in a special way. It ends up giving almost the same as using null . Only that there is separation of the code, which is good for some and bad for others. Then you would have to do the following:

function Exemplo(NullAnimal $animal) {
    echo "não para para fazer nada com este objeto";
}
    
24.09.2015 / 16:23