Search code examples
swiftfunctionstandards

Is a Separate Function Preferred for 2 Lines of Repeated Code in Swift?


I am designing a small game, and have decided on an initial way to distribute points based on the number of seconds elapsed between the time a question was asked and an enter button was pressed.

I understand that best practice is to create a function to call when lines are going to be repeated, but it seems to me that it may be a little excessive to call it when there are only two lines repeated four times. Using the code below, would it be "proper" or preferred for me to create a function for the last two lines in each section?

//Assigns points to score based on elapsed time and updates score
func updateScore() {

    timer.invalidate()

    if timeToAnswer < 3 {
        questionScore = 10  //10 points for answering so quickly
        score = score + questionScore  //Updates score
        timeToAnswer = 0  //Resets var timeToAnswer
    }

    else if (timeToAnswer >= 3) && (timeToAnswer < 6) {
        questionScore = 7
        score = score + questionScore
        timeToAnswer = 0
    }

    else if (timeToAnswer >= 6) && (timeToAnswer < 11) {
        questionScore = 10 - timeToAnswer
        score = score + questionScore
        timeToAnswer = 0
    }

    else {
        questionScore = 1
        score = score + questionScore
        timeToAnswer = 0
    }
}

Thank you very much to anybody that offers assistance or advice.


Solution

  • You can do it in a better way. You can use switch statement, too. Anyway:

    func updateScore() {
    
        timer.invalidate()
    
        if timeToAnswer < 3 {
            questionScore = 10
        }
    
        else if (timeToAnswer >= 3) && (timeToAnswer < 6) {
            questionScore = 7
        }
    
        else if (timeToAnswer >= 6) && (timeToAnswer < 11) {
            questionScore = 10 - timeToAnswer
        }
    
        else {
            questionScore = 1
        }
    
        score = score + questionScore  //Updates score
        timeToAnswer = 0  //Resets var timeToAnswer
    }