Error checking shouldn't be compensation for bad code

When writing code for SubmitGuess, one of the validity checks is length. In the video, if the length is not validated, a shorter guess will throw an exception (the application blows a gasket).

That should never happen. I don’t know yet if this was corrected in a later lecture, but this is what I see now.

The code should be written robustly to handle preventable code based issues:

The start of the function:

FBullCowCount FBullCowGame::SubmitGuess(FString Guess)
{
// incriment the turn number
MyCurrentTry++;

// setup a return variable
FBullCowCount BullCowCount;

// loop through all letters in the guess
int32 HiddenWordLength = MyHiddenWord.length();
for (int32 MHWChar = 0; MHWChar < HiddenWordLength; MHWChar++) {
	// compare letters against the hidden word
	for (int32 GChar = 0; GChar < HiddenWordLength; GChar++) {

This code assumes that the guess and the hidden word are always the same length. Yes, the validity function makes sure of this, but only if the developer chooses to use that function. If the check for length is not in the same function to check for bulls and cows, the code should never assume that they are. It’s a bit of CYA programming, but on a large project, you may not ever meet the person who uses your code; so make it safe.

It should be:

FBullCowCount FBullCowGame::SubmitGuess(FString Guess)
{

    // increments the turn number
    MyCurrentTry++;
    // sey up a return value
    FBullCowCount BullCowCount;
    //get length of hidden word
    int32 HiddenWordLength = (int32) MyHiddenWord.length();
    //get length of user's guess
    int32 GuessWordLength = (int32) Guess.length();

    //loop through all letters in the guess
    for(int32 GChar = 0; GChar < GuessWordLength; GChar++)
    {
        // compare letters against the hidden word
        for(int32 MHWChar = 0; MHWChar < HiddenWordLength; MHWChar++)

etc…

1 Like

I agree with the policy. However, the game requires an alphabetic isogram of the correct length for a valid try. So it will be prevented by the time it is all sorted out.

I think the reason for this rather peculiar way of using the debugger as some sort of test-first development is because we are not working on the view yet and there is no sort of consideration of preconditions and assuring their satisfaction. I suppose this is the sort of thing that Dijsktra considered dreadful.

I notice that my way of thinking through this part of the game led me to a completely different approach. Consequently, I ended up not needing enumerations and thereby lost an opportunity to use a switch statement in PlayGame() [;<). Interesting trade-off.

Privacy & Terms