...

Handle Edge Cases in Programming

Rate this post

As the name suggests, look for edges cases, let us understand with an example

First Solution:

// language : golang
maxValue := 0
for i := 0; i <= len(array); i++ {
	if maxValue < array[i] {
		maxValue = array[i]
	}
}
return maxValue

Above code will crash when i = len(array) because array index will range from 0 to len(array) -1 (not len(array))

Correct solution

maxValue := 0
for i := 0; i < len(array); i++ {
	if maxValue < array[i] {
		maxValue = array[i]
	}
}
return maxValue

Example 2 – For doing any operation in matrix for each cell we need to check that it’s index is valid at the start of the function as below:-

// other code parts

import "errors"

var (
     ErrRowOutOfBounds = errors.New("cell' row out of bounds")
     ErrColOutOfBounds = errors.New("cell' column out of bounds")
)

func opInMatrix(i, j, numRows, numCols int, matrix [][]int) error {
      if i < 0 || i >= numRows {
            return ErrRowOutOfBounds 
     }
      if j < 0 || j >= numCols {
            return ErrColOutOfBounds 
     }
   
    /// do the actual operation
}
Spread the love

Leave a Comment

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.