-1

I'm developing a project with domain objects that contains quite a few fields. The fields only store numbers as codes or IDs.

To display these domain objects, I have to write some logic to convert the codes to display labels.

Now, with my most straightforward thoughts, I'd just write a utility class to do the conversion.

However, since this should be a very common cases, I am just wondering is there any better practice for doing this kind of job? (in a more object-oriented way)

Is there any design pattens for this context?

Thank you so much!

2 Answers2

0

I don't like the concept of utility classes. The utility closet is where you dump anything you don't have a label for. You do have a label for this action. Serializer or Labeler.

Create an interface Serializer or Labeler or whatever, and implement it however many times as needed (if there are domain objects which don't serialize the same, or if you need extra functionality).


Another approach would be to have your domain object serialize themselves, in which case any serializable object can implement a Serializable interface, and your rendering function can accept only Serializable objects.

Similar to the comparable vs comparator debate.

Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
  • thanks for ur comment! As to your suggestion, could it also be used in the case where we want to label the IDs separately? For example, for a class Person with occupation & sex, i'd like to convert occupation 0 to "Teachers", 1 to "Engineers", 2 to "Solders", and convert sex 0 to "Female", 1 to "Male". – John the Traveler Nov 16 '15 at 15:38
  • The reason i'm asking this is because Serializable sounds like a way to dump the whole object to a String representation I want. But what I want is a more delicate way to convert each field as needed – John the Traveler Nov 16 '15 at 15:40
0

Almost sounds like a "foreign key" or a "dictionary" or a "map".
Mapping a "occupation" of "0" to "Teacher".
Mapping a "sex" of "0" to "Female".

If you have enough data, you could just dump it into a database ... perform a lookup, and dump the result:

field-name, value, text 
"occupation", 0, "Teacher"
"occupation", 1,"Engineer" 
"sex", 0, "Female"

Then, you can "easily" (ha ha) add more and more to the database table as you need to.

Of course there are "many ways to skin a cat" ... you could just have a code file that has a dictionary/map in it to do the exact same lookup. You can "easily" (ha ha) add more to the code file.

DanBaker
  • 582
  • 4
  • 13