I don't understand the reason for this lesson

In this lesson, a lot of the code was refactored, mainly by moving the majority of the code from the OnInput function to a new function, ProcessGuess. I don’t understand why there is a need to do this, why move code from an already working function to a new one? Is it to make the code look cleaner or is there some other purpose for moving the code?

Speaking of clean code, currently, would the code written in the lesson be considered as clean code?
This is the code as written in the lesson:

// Fill out your copyright notice in the Description page of Project Settings.
#include "BullCowCartridge.h"

void UBullCowCartridge::BeginPlay() // When the game starts
{
    Super::BeginPlay();
    SetupGame();   
}

void UBullCowCartridge::OnInput(const FString& Input) // When the player hits enter
{
    ClearScreen();
    // Checking PlayerGuess
    if (bGameOver)
    {
        ClearScreen();
        SetupGame();
    }
    else // Checking PlayerGuess
    {
        ProcessGuess(Input);
    }
    
}
    
void UBullCowCartridge::SetupGame()
{
    // Welcoming The Player
    PrintLine(TEXT("Welcome to Bull Cows!"));

    HiddenWord = TEXT("cakes");
    lives = HiddenWord.Len();
    bGameOver = false;
    PrintLine(TEXT("Guess the %i letter word!"), HiddenWord.Len());
    PrintLine(TEXT("You have %i lives."), lives);
    PrintLine(TEXT("Type in your guess and \npress enter to continue...")); // Prompt Player For Guess
}

void UBullCowCartridge::EndGame()
{
    bGameOver = true;
    PrintLine(TEXT("Press enter to play again."));
}

void UBullCowCartridge::ProcessGuess(FString Guess)
{
    if (Guess == HiddenWord)
    {
        PrintLine(TEXT("You have Won!"));
        EndGame();
        return;
    }
    if (Guess.Len() != HiddenWord.Len())
    {
        PrintLine(TEXT("Sorry wrong number of characters, try guessing again!"));
        PrintLine(TEXT("The word is %i characters long"), HiddenWord.Len());
        PrintLine(TEXT("You have %i lives remaining"), lives);
        return;
    }

    PrintLine(TEXT("Lost a life!"));
    PrintLine(TEXT("%i"), --lives);

    if (lives <= 0)
    {
        PrintLine(TEXT("You have no lives left!"));
        PrintLine(TEXT("The hidden word was: %s"), *HiddenWord);
        EndGame();
        return;
    }

    // Show number of Bulls and Cows
    PrintLine(TEXT("Trying guessing again, you have %i lives left"), lives);
}

Yes. It makes the code easier to grok. You could even extract out the checks to it’s own function so that process guess could become

if (IsValid(Guess))
{
    // deal with lives and bulls/cows
}
else
{
    // print that they didn't enter a valid guess (or do that in IsValid)
}

And would make it potentially even easier sift through.

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

Privacy & Terms