Best practice for invalid delete method parameters

So, I have an abstract data type called RegionModel with a series of values ​​(Region), each of which maps to an index. You can delete several areas by calling:

regionModel.removeRegions(index, numberOfRegionsToRemove);

My question is the best way to handle the call when the index is valid:

(between 0 (inclusive) and the number of areas in the model (excluding))

but the number ofOfRegionsToRemove is not valid:

(index + regionsToRemove> the number of regions in the model)

Is it better to throw an exception like IllegalArgumentException, or just delete as many areas as I can (all regions from index to end of model)?

Subprocess: if I throw an exception, what is the recommended way for the unit test that the call throws an exception and leaves the model untouched (I use Java and JUnit here, but I assume this is not a Java specific issue).

+3
source share
3 answers

I agree with Mitchel and casperOne - The exception makes the most sense.

Regarding unit testing, JUnit4 allows you to directly exclude: http://www.ibm.com/developerworks/java/library/j-junit4.html

You will only need to pass parameters that guarantee the cause of the exception, and add the correct annotation ( @Test(expected=IllegalArgumentException.class)) to the JUnit testing method.

. , JUnit 4 - JUnit 3. , JUnit 3. .

- try/catch Assert.

- (, regionModel , ), :

public void testRemoveRegionsInvalidInputs() {
  int originalSize = regionModel.length();
  int index = 0;
  int numberOfRegionsToRemove = 1,000; // > than regionModel current size
  try {
    regionModel.removeRegions(index, numberOfRegionsToRemove);

    // Since the exception will immediately go into the 'catch' block this code will only run if the IllegalArgumentException wasn't thrown
    Assert.assertTrue("Exception not Thrown!", false);
  }
  catch (IllegalArgumentException e) {
     Assert.assertTrue("Exception thrown, but regionModel was modified", regionModel.length() == originalSize);
  }
  catch (Exception e) {
      Assert.assertTrue("Incorrect exception thrown", false);
  }
}
+1

, remove, , , .

, , . , , ( ) .

+2

I would say that an argument like an illegalArgumentException would be the best way. If the calling code did not pass a workable value, you would not have to believe that they really wanted to delete what they did.

+1
source

Source: https://habr.com/ru/post/1706127/


All Articles