Jump to content


Photo

Difference Between Two Methods


  • Please log in to reply
1 reply to this topic

#1 darivuki

darivuki

    New Member

  • Members
  • Pip
  • 7 posts

Posted 04 July 2014 - 02:15 PM

Hello!

Regarding performance and best practice in writing code, is there a big difference between these two implementations of the same method?

Here is the code: http://pastebin.com/Z02hhHW4

It's the Attack method for the Blue Potion in the second Lab (3rd edition)

#2 AndrewStellman

AndrewStellman

    Andrew Stellman

  • O'Reilly Author
  • PipPipPipPipPipPipPipPipPipPipPip
  • 811 posts
  • Gender:Male
  • Location:Brooklyn, NY
  • Interests:Author of: "Head First C#", "Beautiful Teams", "Head First PMP", "Applied Software Project Management"

Posted 07 July 2014 - 04:09 PM

Strange -- I wrote a reply to this yesterday, but it seems to have disappeared.

Since you're not using the "direction" parameter, why not just ignore it? Do something like this:

public override void Attack(Direction direction, Random random)
{
    if (someDirection == direction && game.CheckPlayerInventory("Blue Potion"))
        game.IncreasePlayerHealth(5, random);
}

As far as your two methods go, a couple of comments. With the case statement, instead of repeating the same code for four different cases, you can collapse them down:

switch (direction)
{
    case Direction.Up:
    case Direction.Down:
    case Direction.Left:
    case Direction.Right:
        if (game.CheckPlayerInventory("Blue Potion"))
            game.IncreasePlayerHealth(5, random);
        break;
}

As far as the foreach goes:

public override void Attack(Direction direction, Random random)
{
    foreach (Direction someDirection in Enum.GetValues(typeof(Direction)))
    {
        if (someDirection == direction && game.CheckPlayerInventory("Blue Potion"))
            game.IncreasePlayerHealth(5, random);
        else
            return;
    }

This actually has a problem in it. What happens if you pass it Direction.Left, and the first value in the Direction enum is Up? The foreach will do this check:
if (someDirection == direction && game.CheckPlayerInventory("Blue Potion"))
since someDirection is Up and direction is Left, it will jump to the else block, which will return out of the function without increasing the player's health.

I hope this helps!
Andrew Stellman
Author, Head First C#
Building Better Software -- http://www.stellman-greene.com




0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users