質問

I'm designing a Monopoly game while also reading up more on OO principles. I was reading about the LSP (Liskov Substitution Principle) and found that either I'm not fully understanding it or am violating it and should change my design.

(Just a note: this project is personal and just for fun, so I don't actually care how maintainable the code is, but I'm just asking for personal education and understanding of LSP)

Let me begin with what I've designed thus far:

Class BoardSpace is an abstract base class, and there is one subclass per "kind" of space on the board. So I have PropertySpace, TaxSpace, GoSpace, etc.

BoardSpace has info about where the space is on the board, and also an abstract void Land() method, so that each different space can do something different when landed on, as it should. That way when I'm calling Land() on the current BoardSpace object, it doesn't need to care or think about anything else and just does what the space should do. To me this makes sense and sounds like a workable solution.

But it seems to go against LSP in that all these different Land() overridden methods will do entirely different things, as I've designed them to do.

Or am I misunderstanding LSP? Does it have more to do with the way Land() is "expected" or "described" to work? Which in this case is completely different per space so that's okay? Or is it certainly a violation and I should redesign it?

Side question: would this be considered an "abuse" of inheritance or a good use of it?

役に立ちましたか?

解決

Under LSP it is fine for subclass methods to do completely different things from the superclass ones as long as they do not violate the contract of the superclass. So really it all depends on how broad you make that contract.

If BoardSpace.Land() was only allowed to change the state of the player, then you would have a problem if landing a subclass allowed the player to buy it (changing the state of the space). If however Land() is allowed to change the state of the landing player and the owning player, the state of the space, and the state of the card decks, then there is no violation of LSP.

Still, it might be good practice to break things up into smaller methods that you can reason about more exactly. For example, the space might have a special action taken on it when you land (like drawing a card), followed by a transaction between the player and the owner of the space (other player or bank), with the constraint that the action can only affect the cash and cards of the player and the card decks, and the transaction can only affect the money of the two involved parties and the ownership of the space.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top