문제

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

다른 팁

You can veto an update to a property by throwing a PropertyVetoException. See here for an example and explanation: http://weblogs.java.net/blog/malenkov/archive/2007/11/how_to_veto_a_p.html

Its always better to validate the input during the time of its entry. Using Getter and Setter is a good option. So during the assignment of the data to the instance variable, its type and other parameters can be checked.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top