I was working on a problem not too long ago, and the topic of responsibilities and where they should go came up. In my linked problem, the University is the institution and class that holds all the rules and ensures that each student registering, has the required documents.
This made me recall a blog post by Eric Lippert: Wizards and Warriors.
It reads:
We keep on talking about “rules”, and so apparently the business domain of this program includes something called a “rule”, and those rules interact with all the other objects in the business domain. So then should “rule” be a class? I don’t see why not! It is what the program is fundamentally about. It seems likely that there could be hundreds or thousands of these rules, and that they could change over time, so it seems reasonable to encode them as classes.
The Rules:
A warrior can only use a sword.
A wizard can only use a staff.
My problem is how would I determine in the GameRules
class
the specific object being passed to verify if I can carry it?
public final class GameRules {
public static boolean verifyifwizardcancarry(Weapon weapon){
boolean canCarry = false
if weapon is a a staff set canCarry to true
return canCarry;
}
}
public abstract class Player{
private List<Weapon> weapons;
// constructor and OOP goodness left out
public abstract void add(Weapon weapon);
}
public final class Wizard extends Player{
@Override
public void add(Weapon weapon){
if(GameRules.verifyifwizardcancarry(weapon){
// - code to add weapon to inventory
}
}
}
How can I verify that the Weapon
being passed to the GameRules
class
is in fact a Sword
? From reading, the use of instanceof
or getClass()
is considered code smell.
I found this answer, but it violates LSP and goes against what the blog states, that it shouldn't throw an exception, and doesn't really answer my question.