5

I'm currently making a game were you have to defend a castle. Each level consists out of lanes were enemies come in and attack it. Now, the castle is the same for every level, if it gets damaged in level 1, it will "spawn" in level 2 with the same health points. So what I did was on the start of the game create one castle object and keep this for the rest of the game.

Here's an illustration to clarify my "design":

enter image description here

Now when an enemy arrives at the castle and damages it my codes looks like this:

this.getLane().getLevel().getGame().getCastle().doDamage(1);

Which doesn't really look very good. I've been looking in some design patterns to come up with a cleaner solution but I didn't really find one and was wondering if someone has an idea.

(I know there's this question about chaining getters out there aswell: https://stackoverflow.com/questions/8744668/java-getter-chaining-bad-or-good but it doesn't really come up with a solution)

Community
  • 1
  • 1
maigelm
  • 445
  • 4
  • 13
  • I added the [tag:law-of-demeter] as a tag, since this question is essentially tied to that principle. As such, check out http://stackoverflow.com/questions/163071/coupling-cohesion-and-the-law-of-demeter – Fuhrmanator Apr 26 '14 at 21:42

1 Answers1

5

One way to convert this:

this.getLane().getLevel().getGame().getCastle().doDamage(1);

to this:

this.doDamage(1);

would be to write a doDamage method for the Game, Level, and Lane classes. This will work if you have a limited number of chained calls.

The Game class method would look like this:

public void doDamage(int damage) {
    getCastle().doDamage(damage);
}

and so on for the Level and Lane classes.

Gilbert Le Blanc
  • 50,182
  • 6
  • 67
  • 111
  • 1
    Isn't this a violation to responsibilities? It doesn't really seem to make sense to me for the Lane class to have a doDamage() method. – maigelm Apr 25 '14 at 16:07
  • @user2423268: Perhaps. It's your choice how you want to deal with damage. If you have a hierarchy of classes, you'll have chained method calls. If you don't want chained method calls, I've outlined one way to get rid of them. Another way would be to let the enemy deal directly with castles and hide the internal organization. – Gilbert Le Blanc Apr 25 '14 at 16:10
  • @user2423268: One limitation in languages and frameworks which are based on Promiscuous Object References is that by the time the right side of a "dot" is looked at, the left side's role in the expression is done. What's really needed is an efficient way of having the left-side get notified when the right side is done without having to worry about attaching and detaching events. – supercat Apr 29 '14 at 22:26