O'Reilly Forums: Difference Between Two Methods - O'Reilly Forums

Jump to content

Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

Difference Between Two Methods

#1 User is offline   darivuki 

  • New Member
  • Pip
  • Group: Members
  • Posts: 7
  • Joined: 18-March 14

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)
0

#2 User is offline   AndrewStellman 

  • Andrew Stellman
  • PipPipPipPipPipPipPipPipPipPipPip
  • Group: O'Reilly Author
  • Posts: 738
  • Joined: 08-October 08
  • 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

Share this topic:


Page 1 of 1
  • You cannot start a new topic
  • You cannot reply to this topic

1 User(s) are reading this topic
0 members, 1 guests, 0 anonymous users