So I have an abstract data type called RegionModel with a series of values (Region), each mapped to an index. It’s possible to remove a number of regions by calling:
regionModel.removeRegions(index, numberOfRegionsToRemove);
My question is what’s the best way to handle a call when the index is valid :
(between 0 (inclusive) and the number of Regions in the model (exclusive))
but the numberOfRegionsToRemove is invalid:
(index + regionsToRemove > the number of regions in the model)
Is it best to throw an exception like IllegalArgumentException or just to remove as many Regions as I can (all the regions from index to the end of the model)?
Sub-question: if I throw an exception what’s the recommended way to unit test that the call threw the exception and left the model untouched (I’m using Java and JUnit here but I guess this isn’t a Java specific question).
I agree with Mitchel and casperOne — an Exception makes the most sense.
As far as unit testing is concerned, JUnit4 allows you to exceptions directly: http://www.ibm.com/developerworks/java/library/j-junit4.html
You would need only to pass parameters which are guaranteed to cause the exception, and add the correct annotation (
@Test(expected=IllegalArgumentException.class)) to the JUnit test method.Edit: As Tom Martin mentioned, JUnit 4 is a decent-sized step away from JUnit 3. It is, however, possible to also test exceptions using JUnit 3. It’s just not as easy.
One of the ways I’ve tested exceptions is by using a
try/catchblock within the class itself, and embeddingAssertstatements within it.Here’s a simple example — it’s not complete (e.g. regionModel is assumed to be instantiated), but it should get the idea across: