API Design - Mixing in pre-condition checks for index out of bounds?

Viewed 215

I am designing an API that does something like this:

// Drop $howMany items from after $from 
def dropElements[T](array: Array[T], from: Int, howMany: Int)

The expected behaviour is that howMany should be non-negative and if howMany is zero, it should not do any modification. I have 2 ways to implement this:

def dropElements[T](array: Array[T], from: Int, howMany: Int) {
  assert(howMany >= 0);
  if (howMany == 0) return;
  assert(0 <= from && from < array.length);
  ....   
}

OR:

def dropElements[T](array: Array[T], from: Int, howMany: Int) {
  assert(howMany >= 0);
  assert(0 <= from && from < array.length);
  if (howMany == 0) return;
  ....   
}

I am in favor of the 2nd approach (declaring your preconditions upfront) vs the 1st approach but I was pointed out that the 1st approach is more respectful of the requirements when howMany = 0.

Any thoughts or pros/cons? I am asking as a designer of a standard collections library

5 Answers
Related