views:

72

answers:

3

Is there an easy way/library to check and adjust parameters to stay inside the lists boundaries?

Here a long sample:

if (fromIndex < 0) {
  fromIndex = 0;
}
if (fromIndex > list.size() - 1) {
  fromIndex = list.size() - 1;
}

if (toIndex < 0) {
  toIndex = 0;
}
if (toIndex > list.size() - 1) {
  toIndex = list.size() - 1;
}

list.subList(fromIndex, toIndex);

I know i could move list.size() - 1 to a variable and do an extract-method on the index checks to remove redundant code. But it still seems a bit verbose for this simple task.

+5  A: 
public int sanitize(int index) {
  return Math.max(0, Math.min(index, this.length-1));
}
Zed
little note: `list` or `listSize` should also be a parameter
naltatis
@tatilans: true, in the context of this snippet that looks a bit like a static method. However Brian's suggestion to wrap an existing list is a much much better way to realise this (more flexible, less intrusive, less boilerplate code) and in that case `list` would likely be a final member field.
Andrzej Doyle
OK. I changed it to this.length. If it just adds more confusion I will roll back :)
Zed
+3  A: 

If you want to check all accesses to your list, it seems to me you want to wrap your list within a class implementing the List interface and intercept the accessor methods to check/modify the accessor indices.

e.g.

List sanitised = new SanitisedList(existingList);

This is an example of the Decorator pattern. Note how you just need one class defined (SanitisedList) and you can apply that to any list you have. Use Zed's answer for a nice tidy bounds check.

Brian Agnew
A: 

You could use the ternary operator:

int listMax = list.size() - 1;
list.subList( fromIndex < 0 ? 0 : (fromIndex > listMax) ? listMax : fromIndex, 
              toIndex < 0 ? 0 : (toIndex > listMax) ? listMax : toIndex );
B Johnson