I've created some custom bean classes for custom datatypes in my application such as Address
, PhoneNumber
, SpecialCode
, etc.
These custom non-primitive datatypes has there own restrictions which I want to apply with them, for example think of a PhoneNumber
:
public class PhoneNumber {
private String stdCode;
private String number;
public PhoneNumber() {
}
public PhoneNumber(String stdCode, String number) {
this.stdCode = stdCode;
this.number = number;
}
/* getters and setters */
}
Now what makes me confused is the restrictions on a PhoneNumber
, i.e., I want to make sure the stdCode
must start with a 0
, or the number
must be 7
or 8
digits long, etc.
So, where do apply these rules?
In the constructor? As:
//Custom costructor
public PhoneNumber(String stdCode, String number) {
if (!stdCode.matches("[0-9]+") || !number.matches("[0-9]+")){
throw new IllegalArgumentException("Error in Parsing. The STD Code and Number MUST be numeric digits.");
}
if (!"0".equals(stdCode.substring(1, 2))){
throw new IllegalArgumentException("The STD Code must begins with 0");
}
if (stdCode.length() < 3 || stdCode.length() > 5){
throw new IllegalArgumentException("The STD Code must be 3 to 5 digits long. Current Number of digits: " + stdCode.length() + ". ");
}
this.stdCode = stdCode;
this.number = number;
}
Or there can be custom exceptions also? And where should I merge those custom exceptions with my bean classes?
I am not an experienced programmer and would like to know about what design pattern should I apply here?
you should create getters & setters for your phone # parts and do you validation checking in the setters