mengdiwang / guava-libraries

Automatically exported from code.google.com/p/guava-libraries
Apache License 2.0
0 stars 0 forks source link

Preconditions.checkElementIndex with descTemplate and descArgs #523

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
It seems for me that Preconditions class missing checkElementIndex() method 
with template and varargs just like for checkArgument() or checkNotNull() 
methods.

I suggest this implementation:
 /**
  * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size
  * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive.
  * 
  * @param index a user-supplied index identifying an element of an array, list or string
  * @param size the size of that array, list or string
  * @param descTemplate the message template to use to describe this index in an error message
  * @param descArgs the arguments to be substituted into the message template.
  * @return the value of {@code index}
  * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size}
  * @throws IllegalArgumentException if {@code size} is negative
  */
 public static int checkElementIndex(int index, int size,
                                      @Nullable String descTemplate,
                                      @Nullable Object... descArgs){
  // Carefully optimized for execution by hotspot (explanatory comment above)
  if (index < 0 || index >= size){
   throw new IndexOutOfBoundsException(badElementIndex(index, size, format(descTemplate, descArgs)));
  }
  return index;
 }

Original issue reported on code.google.com by kua...@gmail.com on 21 Jan 2011 at 9:51

GoogleCodeExporter commented 9 years ago
I think this is intentional... unlike checkArgument and checkNotNull, 
checkElementIndex and checkPositionIndex already use specific message formats 
since they check conditions they know how to describe. The "desc" field is just 
there to allow you to replace "index" with something else in the error messages 
rather than for formatting a full message. I imagine it wouldn't be very useful 
to be able to use a format and args in the replacement for "index".

Original comment by cgdec...@gmail.com on 21 Jan 2011 at 6:01

GoogleCodeExporter commented 9 years ago
What he said.  Thanks for the report.

Original comment by kevinb@google.com on 22 Jan 2011 at 7:00

GoogleCodeExporter commented 9 years ago
This issue has been migrated to GitHub.

It can be found at https://github.com/google/guava/issues/<id>

Original comment by cgdecker@google.com on 1 Nov 2014 at 4:15

GoogleCodeExporter commented 9 years ago

Original comment by cgdecker@google.com on 3 Nov 2014 at 9:09