Skip to content

Commit

Permalink
better validation added to PLZ ctor
Browse files Browse the repository at this point in the history
  • Loading branch information
oboehm committed Apr 12, 2017
1 parent 9488bc1 commit 5046e3f
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 7 deletions.
34 changes: 27 additions & 7 deletions src/main/java/de/jfachwert/post/PLZ.java
Expand Up @@ -38,7 +38,7 @@ public class PLZ extends AbstractFachwert<String> {
* @param plz z.B. "70839" oder "D-70839"
*/
public PLZ(String plz) {
super(normalize(plz));
super(validate(plz));
}

private static String validate(String code) {
Expand All @@ -51,21 +51,25 @@ private static String validate(String code) {

private static String validateNumberOf(String plz) {
String kennung = getLandeskennung(plz);
String zahl = getPostleitZahl(plz);
switch (kennung) {
case "D":
if (plz.length() != 6) {
throw new IllegalArgumentException(toLongString(plz) + ": nur 5 Ziffern fuer PLZ sind erlaubt");
}
validateNumberWith(5, kennung, zahl);
break;
case "A":
case "CH":
if (plz.length() != 6) {
throw new IllegalArgumentException(toLongString(plz) + ": nur 4 Ziffern fuer PLZ sind erlaubt");
}
validateNumberWith(4, kennung, zahl);
break;
}
return plz;
}

private static void validateNumberWith(int length, String kennung, String zahl) {
if (zahl.length() != length) {
throw new IllegalArgumentException(zahl + ": nur " + length + " Ziffern fuer PLZ sind erlaubt in " + kennung);
}
}

private static String normalize(String plz) {
return StringUtils.replaceChars(plz, " -", "").toUpperCase();
}
Expand Down Expand Up @@ -117,6 +121,22 @@ public Locale getLand() {
}
}

/**
* Liefert die eigentliche Postleitzahl ohne Landeskennung.
*
* @return z,B. "01001"
*/
public String getPostleitZahl() {
return getPostleitZahl(this.getCode());
}

private static String getPostleitZahl(String plz) {
if (!hasLandeskennung(plz)) {
return plz;
}
return StringUtils.substringAfter(toLongString(plz), "-");
}

/**
* Liefert die PLZ in kompakter Schreibweise (ohne Trennzeichen zwischen
* Landeskennung und eigentlicher PLZ) zurueck.
Expand Down
18 changes: 18 additions & 0 deletions src/test/java/de/jfachwert/post/PLZTest.java
Expand Up @@ -41,6 +41,15 @@ protected Fachwert createFachwert() {
return new PLZ("D-70839");
}

/**
* Postleitzahlen in Oesterreich sind 4-stellig. D.h. eine 5-stellige
* oesterreichische PLZ sollte nicht erstellt werden koennen.
*/
@Test(expected = IllegalArgumentException.class)
public void testInvalidPLZ() {
new PLZ("A-12345");
}

/**
* Test-Methode fuer {@link PLZ#getLandeskennung()}.
*/
Expand Down Expand Up @@ -98,4 +107,13 @@ public void testGetLandCH() {
assertEquals("CH", vaduz.getLand().getCountry());
}

/**
* Test-Methode fuer {@link PLZ#getLand()}.
*/
@Test
public void testGetLandAT() {
PLZ weyer = new PLZ("A-3335");
assertEquals(new Locale("de", "AT"), weyer.getLand());
}

}

0 comments on commit 5046e3f

Please sign in to comment.