A Java version of Simon Brunning's Python and RPG UK postcode splitting algorithms.
Compared to the RPG version, the Java code has the virtue of being readable, even without comments.
Compared with the Python version, the Java is more verbose. Braces aside, this is mainly due to the need to return a whole object in Java where Python returns a simple tuple. The 'guts' of the algorithm is about the same size (7 lines vs 5), thanks to Apache Commons Lang.
import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.builder.ToStringBuilder; public class Postcode { private String inCode = ""; private String outCode = ""; public Postcode(String str) { str = StringUtils.deleteWhitespace(str).toUpperCase(); if (str.length() <= 4) { outCode = str; } else { int outEnd = str.length() - 3; outCode = str.substring(0, outEnd); inCode = str.substring(outEnd); } } public String getInCode() { return inCode; } public String getOutCode() { return outCode; } public String toString() { return ToStringBuilder.reflectionToString(this); } public static void main(String[] args) { System.out.println(new Postcode("SL18jt")); System.out.println(new Postcode("SL1 8jt")); System.out.println(new Postcode("N4")); System.out.println(new Postcode("GN43")); System.out.println(new Postcode("GN43qw")); } }
Comments
While it's not "Java-like", wouldn't returning new String[] { inCode, outCode}; would more accurately match the Python version's functionality?
When in Rome, do as the Romans do. When writing Java, write Java. ;-)
Romanes Eunt Domus!
These Romans, they go the house?
Charles,
In Python, this is not so much viewed as returning a tiny, fixed-length collection as it is returning multiple values. You would use it thus:
outCode, inCode = parse_uk_postcode(str)
James Gosling was thinking about Java's (non-)handling of multivalued returns late last century: http://www.javaworld.com/javaworld/javaone98/j1-98-interview.gosling.html.