In a competition application I'm designing there are several types of prize draw, each of which needs to act upon an entry object in some way. So the first lines of code I wrote defined an interface.
interface PrizeDrawInterface
{
public void enter(EntryInterface entry);
}
Here's the problem which I'm not sure how to solve. It turns out the implementations are going to require more specific objects than EntryInterface
.
class RandomPrizeDraw implements PrizeDrawInterface
{
public void enter(WinnableInterface entry)
{
if (someRandomCondition) {
entry.setWinner(true);
}
}
}
class QuizPrizeDraw implements PrizeDrawInterface
{
public void enter(QuizContestantInterface contestant)
{
if (contestant.getAnswer().isCorrect()) {
contestant.givePrize();
}
}
}
Obviously the above code isn't going to work, as the enter()
method signatures are not compatible.
My current best solution is to add an extra method to the prize draws and delegate type enforcement there, so they might look like this:
class RandomPrizeDraw implements PrizeDrawInterface
{
public void enter(EntryInterface entry)
{
this.doEnter(entry);
}
public void doEnter(WinnableInterface entry)
{
if (someRandomCondition) {
entry.setWinner(true);
}
}
}
But to me this looks more like a quick fix than a clean solution.
Does this problem have a name? Is my interface not fit for purpose? Is there a cleaner solution than the one I have proposed?
this.prizeDraw.enter(entry)
. There's a good chance the language I'll end up using to implement this doesn't support generics :( – Sam Hastings Feb 27 '18 at 22:39if(!(entry is QuizContestantInterface)) throw new Exception("Error - not a valid quiz contestant!");
– user253751 Feb 28 '18 at 5:15