Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the purpose of EmptyIterator?

Tags:

iterator

php

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?

like image 471
Wallace Maxters Avatar asked Sep 24 '15 13:09

Wallace Maxters


1 Answers

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.

like image 78
Rabbit Guy Avatar answered Oct 22 '22 09:10

Rabbit Guy