In PHP Manual, has a class called EmptyIterator
The manual says of the EmptyIterator::rewind()
method:
No operation, nothing to do.
And the other methods of this class throw exceptions or return false
what is the objective of an empty iterator?
This is a Null Object Pattern Class. It is used to literally do nothing and implements an interface just as other objects will of that interface. It makes coding easier in the long run. In other words, because it is not abstract we can make an object out of it and use its methods just as another implemented class of that interface. Example (not my own code, btw):
interface Animal {
public function makeSound();
}
class Dog implements Animal {
public function makeSound() {
echo "WOOF!";
}
}
class Cat implements Animal {
public function makeSound() {
echo "MEOW!";
}
}
class NullAnimal implements Animal { // Null Object Pattern Class
public function makeSound() {
}
}
$animalType = 'donkey';
$animal;
switch($animalType) {
case 'dog' :
$animal = new Dog();
break;
case 'cat' :
$animal = new Cat();
break;
default :
$animal = new NullAnimal();
}
$animal->makeSound(); // won't make any sound bcz animal is 'donkey'
If there was no Null Object Pattern Class then the default would have to do its own thing and skip the following line of code. By making a null object, everything can still be done just fine. We will just make nothing happen when we don't want anything to happen.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With