Both work, so which is better?

Hey everyone,

I was doing the lecture ‘Section 2 Integration Challenge’ and for the challenge of adding in the menu prompt, i came up with something slightly different to the lecturer. My method works, but is there some pitfall that i am not seeing, or is it a valid, just different path.

I defined a method called ReturnToMenu() (Code Below) and called it where necessary (Example Below)

defining ReturnToMenu()

void ReturnToMenu()
    {
        Terminal.WriteLine("Type 'menu' to return to the Main Menu");
        Terminal.WriteLine(" ");
    }

Example of calling ReturnToMenu() Method

void AskForPassword()
    {
        currentScreen = Screen.Password;
        Terminal.ClearScreen();
        SetRandomPassword();
        ReturnToMenu();
        Terminal.WriteLine("Enter your password, hint: " + password.Anagram());
    }

Regards,
Dearte

Your solution it’s perfectly valid and a great one.

The only downfall I see with your code is that it might get a little confusing, the ReturnToMenu method does not return the player to the menu, it only prints a message, so I suggest naming it something else like ReturnMessage or something like that.

1 Like

I like that your code shows a good grasp of method call navigation. It’s the main thing to be learning right now, and it looks like you understand it well. I also find your code very readable, laid out with a series of method calls, which counts for a lot.

As for the merits of Ben’s code in the course:

  1. Ben likes to avoid “magic numbers” when possible. That’s what they call it when you set values (like numbers and text) in your code. It’s a lot easier to manage your code if you avoid magic numbers and use variables instead. These variables can be set just once at or near the top of your script. This way, if you want to change your text later, you don’t have to go digging through your code for every place that you typed this. Instead, you just change it once when you set the variable. I’m kind of surprised he didn’t do the same thing for "Enter your password: "

  2. Technically speaking, const values are more performant because the system knows they never changed and stores them differently. So a const saves you performance, while a method call costs you a bit.

But these are really just academic micro-considerations. It’s not really a reason to do one or the other, especially with a script like this. I think you are doing great n the course right now, both by showing an understanding the content and engaging with the community.

2 Likes

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms