Sunday, February 19, 2012

Stop reinventing wheel, use Apache Commons

Developer's life is full of routine tasks. We need to validate strings, convert data from different formats, compare objects and so on. Some developers tend to write everything on their own, reinventing common algorithms again and again. Every Java developer should look at Apache Commons Lang library as it already has everything we need every day.

When we work with Strings, we usually need to validate them (check if they are not null, not empty or do not contain some specific characters), transform, split, etc.


These tasks can be easily done with the following classes: StringUtils, StringEscapeUtils, RandomStringUtils, Tokenizer, WordUtils.

How often do you check this:

if (str != null && str.trim().length() > 0) {

}


when it can be easily done by:

if (StringUtils.isNotBlank(str)) {

}


List of methods available from StringUtils:

  • IsEmpty/IsBlank - checks if a String contains text
  • Trim/Strip - removes leading and trailing whitespace
  • Equals - compares two strings null-safe
  • IndexOf/LastIndexOf/Contains - null-safe index-of checks
  • IndexOfAny/LastIndexOfAny/IndexOfAnyBut/LastIndexOfAnyBut - index-of any of a set of Strings
  • ContainsOnly/ContainsNone - does String contains only/none of these characters
  • Substring/Left/Right/Mid - null-safe substring extractions
  • SubstringBefore/SubstringAfter/SubstringBetween - substring extraction relative to other strings
  • Split/Join - splits a String into an array of substrings and vice versa
  • Remove/Delete - removes part of a String
  • Replace/Overlay - Searches a String and replaces one String with another
  • Chomp/Chop - removes the last part of a String
  • LeftPad/RightPad/Center/Repeat - pads a String
  • UpperCase/LowerCase/SwapCase/Capitalize/Uncapitalize - changes the case of a String
  • CountMatches - counts the number of occurrences of one String in another
  • IsAlpha/IsNumeric/IsWhitespace/IsAsciiPrintable - checks the characters in a String
  • DefaultString - protects against a null input String
  • Reverse/ReverseDelimited - reverses a String
  • Abbreviate - abbreviates a string using ellipsis
  • Difference - compares two Strings and reports on their differences
  • LevensteinDistance - the number of changes needed to change one String into another


Now let's look at arrays. We check that arrays are not empty, we search for an element in array, we add/remove elements.


ArrayUtils class helps with arrays. My favourite method is ArrayUtils.contains() that checks if an element is in array.

if (ArrayUtils.contains(array, element)) {

} 


ArrayUtils contains commons operations for arrays of every primitive type and arrays of Objects:

Object[] add(Object[] array, int index, Object element)
Inserts the specified element at the specified position in the array.

Object[] add(Object[] array, Object element)
Copies the given array and adds the given element at the end of the new array.

Object[] addAll(Object[] array1, Object[] array2)
Adds all the elements of the given arrays into a new array.

Object[] clone(Object[] array)
Shallow clones an array returning a typecast result and handling null.

boolean contains(Object[] array, Object objectToFind)
Checks if the object is in the given array.

int getLength(Object array)
Returns the length of the specified array.
         
int hashCode(Object array)
Get a hashCode for an array handling multi-dimensional arrays correctly.
         
int indexOf(Object[] array, Object objectToFind)
Finds the index of the given object in the array.
         
int indexOf(Object[] array, Object objectToFind, int startIndex)
Finds the index of the given object in the array starting at the given index.

boolean isEmpty(Object[] array)
Checks if an array of Objects is empty or null.

boolean isEquals(Object array1, Object array2)
Compares two arrays, using equals(), handling multi-dimensional arrays correctly.
         
boolean isSameLength(Object[] array1, Object[] array2)
Checks whether two arrays are the same length, treating null arrays as length 0.

boolean isSameType(Object array1, Object array2)
Checks whether two arrays are the same type taking into account multi-dimensional arrays.
         
int lastIndexOf(Object[] array, Object objectToFind)
Finds the last index of the given object within the array.
         
int lastIndexOf(Object[] array, Object objectToFind, int startIndex)
Finds the last index of the given object in the array starting at the given index.
         
Object[] remove(Object[] array, int index)
Removes the element at the specified position from the specified array.

Object[] removeElement(Object[] array, Object element)
Removes the first occurrence of the specified element from the specified array.
         
void reverse(Object[] array)
Reverses the order of the given array.
         
Object[] subarray(Object[] array, int startIndexInclusive, int endIndexExclusive)
Produces a new array containing the elements between the start and end indices.

Map toMap(Object[] array)
Converts the given array into a Map.

Integer[] toObject(int[] array)
Converts an array of primitive ints to objects.

int[] toPrimitive(Integer[] array)
Converts an array of object Integers to primitives.

int[] toPrimitive(Integer[] array, int valueForNull)
Converts an array of object Integer to primitives handling null.

String toString(Object array)
Outputs an array as a String, treating null as an empty array.
         
String toString(Object array, String stringIfNull)
Outputs an array as a String handling nulls.


Bonus :) The following classes help with building toString(), hashCode() and equals() methods:

  • EqualsBuilder
  • HashCodeBuilder
  • ToStringBuilder

For more detailed info see: http://commons.apache.org/lang/userguide.html


No comments:

Post a Comment