Recently I worked on FindBugs warnings about exposing internal state, i.e. when a reference to an array was returned instead of returning a copy of the array. I created some templates to make converting that code easier.
Which one did you create to support defensive programming and want to share with the SO crowd?
Templates I’ve created so far (as examples):
To create a copy of an array to return from a method:
final ${type}[] ${result} = new ${type}[ ${array}.length ]; System.arraycopy( ${array} , 0 , ${result} , 0 , ${array}.length );
To clone an object:
(${o}!= null?(${type})${o}.clone():null)
I like having as a template a "safer" equals() definition:
To be sure to always avoid Eq: equals method overrides equals in superclass and may not be symmetric (
EQ_OVERRIDING_EQUALS_NOT_SYMMETRIC), where:This is only for classes implementing
Comparableand allows for:compareTo()function);Comparable#compareTo()asking to ensure that(x.compareTo(y)==0) == (x.equals(y))(strongly recommended, but not strictly required though).