How to check a condition after each line of a function?

Viewed 53

Is there a way to check a condition for each line of a function without needing to write a sequence of identical statements?

For example, let's say we are passing through a maze of squares, where each square may randomly have a coin to collect, whereas some squares may not have a coin to collect.

Is there an efficient way to write a function that checks each square for a coin, collects a coin if there is a coin, then moves to the designated next square? I only want to run the collectCoin() method if there is a coin. Otherwise, I just want to check if there's a coin and pass through the square if there isn't a coin.

Here's an example of what I perceive to be an inefficient method:

func collectTheCoins() {
    if isOnCoin {
        collectCoin()
    }
    
    moveForward()
    if isOnCoin {
        collectCoin()
    }
    
    moveRight()
    if isOnCoin {
        collectCoin()
    }
    
    moveLeft()
    if isOnCoin {
        collectCoin()
    }
    
} 

For efficiency purposes, my objective is to only run the collectCoin() method if in fact there is a coin to collect.

1 Answers

If your method collectCoin() always depends on checking whether isOnCoin == true then you won't be able to eliminate the condition but you could place a guard isOnCoin else { return } at the beginning of the collectCoin() method so that your code looks cleaner and without those repetitions.

Example:

func collectCoin() {
    guard isOnCoin else { return }
    // Your collect coin logic
}

func collectTheCoins() {
    collectCoin()
    
    moveForward()
    collectCoin()
    
    moveRight()
    collectCoin()
    
    moveLeft()
    collectCoin()
}

Also, if you always collect a coin after moving you could even place collectCoin() at the end of every of your move methods and get rid of those extra collectCoin() calls after every move method call. You would get something like this:

func moveForward() {
    // Your move forward logic
    collectCoin()
}

func moveRight() {
    // Your move right logic
    collectCoin()
}

func moveLeft() {
    // Your move left logic
    collectCoin()
}

func collectTheCoins() {
    collectCoin()
    moveForward()
    moveRight()
    moveLeft()
}
Related