How can I prepare for similar potential data of a class in future?
I have a class (e.g. Customer
)
name
and a method getName()
.
In this moment, they have only English name
But I have to prepare if there are any new language is available (e.g. French Name)
It seems that I should use Decorator
pattern
Should I just add a hash table or are there any better solutions??
If they have multiple names, then a HashMap would be a reasonable solution
public String getName(String lang) {
return names.get(lang)
}
(error checking elided)
If your customers have multiple name representations, then other entities may also, and you should probably extract that functionality to be used across the system.
Don't people have the same name regardless of the language? Sometimes the name is spoken differently by users of different languages, and written differently in different scripts.
If you really want this complexity you need four concepts: customer, name, pronounciation and written-representation. A customer HAS-A name. A name HAS-AN-ASSOCIATED native pronunication and perhaps HAS-ASSOCIATED alternative pronunciations. A pronunciation might HAVE-A text representation using the International Phonetic Alphabet (IPA). A written-representation is simply a string.
Is that enough to point you in the correct direction?
I agree with Brian if the customer has multiple names.
If you however have English, French and German customers, with perhaps an address (the format differs per country) you could also use interfaces:
interface Address {
void setStreet(String street);
void setPostalCode(String code);
}
interface Customer {
void setName(String name);
void setAddress(Address address);
}
public class EnglishAddress implements Address {
public void setPostalCode(String postalCode) {
// custom checking of the typical English zipcode format
}
...
}
public class FrenchAddress implements Address {
public void setPostalCode(String postalCode) {
// custom checking of the typical French zipcode format
}
}
public class EnglishCustomer implements Customer {
...
}
In such a case you could build your business logic on Address and Customer, and create the correct classes based on user input. Possibly by using a Factory class, though that's entirely optional.
Using such a method you can have country specific validation and meta-information without sacrificing the power of fairly generic business logic operating on customers and addresses.
I wonder if it is the same name but shown differently in different locales? That is a Russian customer's screen would be using a different character set then an American so displaying an American's name would use different characters. Is this the problem you are facing?
精彩评论