Java 17 Recipes
-2. Designing Intelligent Constants
Download 3.2 Mb. Pdf ko'rish
|
Java 17 Recipes
7-2. Designing Intelligent Constants
Problem You need a type that can represent a fixed set of related constants, and you want to build some state and behavior (logic) around your constants in an object-oriented fashion. Chapter 7 Data SourCeS anD ColleCtionS 244 Solution Use an enum type and take advantage of type safety because enum types are full-fledged Java classes. An enum type can have state and behavior just like any other class, and the enum constants, themselves being instances of the enum type, inherit this state and behavior. An example best illustrates this. Let’s expand on the example from the previous recipe. Imagine that you need to process and validate all the fields from an HTML form submitted. Each form field has a unique set of rules for validating its content, based on the field type. For each form field, you have the field’s “name” and the value entered in that form field. The FieldType enum can be expanded to handle this very easily. public enum FieldType { PASSWORD(FieldType.passwordFieldName) { // A password must contain one or more digits, one or more lowercase letters, one or more uppercase letters, and be a minimum of 6 characters in length. public boolean validate(String fieldValue) { return Pattern.matches("((?=.*\\d)(?=.*[a-z]) (?=.*[A- Z]).{6,})", fieldValue); } }, EMAIL_ADDRESS(FieldType.emailFieldName) { // An email address begins with a combination of alphanumeric // Characters, periods, and hyphens, followed by a mandatory // Ampersand ('@') character, followed by a combination of // Alphanumeric characters (hyphens allowed), followed by a // Ane or more periods (to separate domains and subdomains), // And ending in 2-4 lphabetic characters representing // A the domain. public boolean validate(String fieldValue) { return Pattern.matches( "^[\\w\\.-]+@([\\w\\-]+\\.)+[A-Z|a-z] {2,4}$", fieldValue); } }, Chapter 7 Data SourCeS anD ColleCtionS 245 PHONE_NUMBER(FieldType.phoneFieldName) { // A phone number must contain a minium of 7 digits. // Three optional digits representing the area code may appear in // Front of the main 7 digits. The area code may, optionally, // Be surrounded by parenthesis. If an area code is included, // The number may optionally be prefixed by a '1' for // Long distance numbers. Optional hypens my appear after // The country code ('1'), the area code, and the // first 3 digits of the 7 digit number. public boolean validate(String fieldValue) { return Pattern.matches( "^1?[- ]?\\(?(\\d{3})\\)?[- ]?(\\d{3}) [- ]?(\\d{4})$", fieldValue); } }, SOCIAL_SECURITY_NUMBER(FieldType.ssnFieldName) { // A social security number must contain 9 digits with optional // Hyphens after the third and fifth digits. public boolean validate(String fieldValue) { return Pattern.matches("^\\d{3}[- ]?\\d{2}[- ]?\\d{4}$", fieldValue); } }; // End of enum constants definition // Instance members // private String fieldName; // Define static constants to increase type safety static final String passwordFieldName = "password"; static final String emailFieldName = "email"; static final String phoneFieldName = "phone"; static final String ssnFieldName = "ssn"; private FieldType(String fieldName) { this.fieldName = fieldName; } public String getFieldName() { return this.fieldName; } Chapter 7 Data SourCeS anD ColleCtionS 246 abstract boolean validate(String fieldValue); // Static class members // private static final Map new HashMap<>(); static { for (FieldType field : FieldType.values()) { nameToFieldTypeMap.put(field.getFieldName(), field); } } public static FieldType lookup(String fieldName) { return nameToFieldTypeMap.get(fieldName.toLowerCase()); } private static void printValid(FieldType field, String fieldValue, boolean valid) { System.out.println(field.getFieldName() + "(\"" + fieldValue + "\") valid: " + valid); } public static void main(String... args) { String fieldName = FieldType.passwordFieldName; String fieldValue = "1Cxy9"; // invalid - must be at least 6 characters FieldType field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); fieldName = FieldType.phoneFieldName; fieldValue = "1-800-555-1234"; // valid field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); fieldName = FieldType.emailFieldName; fieldValue = "john@doe"; // invalid - missing . field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); fieldName = FieldType.ssnFieldName; fieldValue = "111-11-1111"; // valid Chapter 7 Data SourCeS anD ColleCtionS 247 field = lookup(fieldName); printValid(field, fieldValue, field.validate(fieldValue)); } } Running the preceding code results in the following output. password("1Cxy9") valid: false phone("1-800-555-1234") valid: true email("john@doe") valid: false ssn("111-11-1111") valid: true Download 3.2 Mb. Do'stlaringiz bilan baham: |
Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling
ma'muriyatiga murojaat qiling