Duplicated code/design pattern missed?

In my OPML parsing class I have the following method:

bc. function getBlog()
{
static $count = 0;
static $total;

if ($total == ”) {
$total = count($this->data);
}

if ($total == $count) {
return false;
}
$blog = &new Blog($this->data[$count]);
$count++;
return $blog;
}

and in the Blog class I have:

bc. function getEntry()
{
static $count = 0;
static $total;

if ($total == ”) {
$total = count($this->data);
}

if ($total == $count) {
return false;
}
$item = &new Item($this->data[$count]);
$count++;
return $item;
}

Pretty much repeated code. Which is going to appear in many other classes as well.

So how can I factor this out? Is there a design pattern that should be used here? Or is this a duplication of code I have to live with?

2 comments ↓

#1 Rémy on 10.15.03 at 11:07 pm

Mmmmm… It looks like a iterator-pattern to me.

$it =& new Iterator($blogs);
for ($it->reset(); $it->isValid(); $it->next())
{
$blog =& $it->getCurrent();
doSomethingWith($blog);
}

#2 Barry on 11.21.03 at 8:53 am

It looks like Blog IS_An item to me; I see inheritance…

Perhaps you can make a baseclass called item and let Blog extend it?

Leave a Comment