I wrote some code which consists of a set of objects which implement a simple interface. These objects are just plain DTO's. They need to rendered. Each one requires it's own renderer. I initially think OK so there will be a renderer interface which has one method render and it will accept an result ResultInterface. Each result item has different pieces of extra data which need to be rendered.
So what actually happens is that each renderer then checks it receives the correct type. So although it seems it accepts anything implementing ResultInterface it actually doesn't. Then I think, well why do I even bother type hinting on ResultInterface.
Here are a few examples to illustrate:
<?php
Interface Renderer
{
public function render(ResultInterface $result);
}
class ExceptionFailureRenderer
{
public function render(ResultInterface $result)
{
if (!$result instanceof ExceptionFailure) {
throw new InvalidArgumentException;
}
}
}
class SomeOtherFailureRenderer
{
public function render(ResultInterface $result)
{
if (!$result instanceof SomeOtherFailure) {
throw new InvalidArgumentException;
}
}
}
Interface ResultInterface
{
public function getName();
}
class ExceptionFailure implements ResultInterface
{
public function getName()
{
return 'Exception Failure';
}
public function getException()
{
return $this->exception;
}
}
class SomeOtherFailure implements ResultInterface
{
public function getName()
{
return 'Some Other Failure';
}
public function getSomeOtherPieceOfData()
{
return $this->importantData;
}
}
$renderers = [
ExceptionFailure::class => new ExceptionFailureRenderer,
SomeOtherFailure::class => new SomeOtherFailureRenderer
];
$output = '';
foreach ($results as $result) {
$renderer = $renderers[get_class($result)];
$output .= $renderers->render($result);
}
I don't think I am using correctly interfaces.
- Should I be using interfaces here?
- Should each
ResultInterfaceitem be responsible for rendering itself? (I think that rendering should be a separate affair personally) ? - Does it really matter?
- Would you design the code differently?
What I have works fine, I am just interested in how other people would approach this.
Aucun commentaire:
Enregistrer un commentaire