tabdulla
tabdulla

Reputation: 525

Structural design pattern

I'm working with three separate classes: Group, Segment and Field. Each group is a collection of one or more segments, and each segment is a collection of one or more fields. There are different types of fields that subclass the Field base class. There are also different types of segments that are all subclasses of the Segment base class. The subclasses define the types of fields expected in the segment. In any segment, some of the fields defined must have values inputted, while some can be left out. I'm not sure where to store this metadata (whether a given field in a segment is optional or mandatory.)

What is the most clean way to store this metadata?

Upvotes: 1

Views: 605

Answers (3)

Sam Goldberg
Sam Goldberg

Reputation: 6801

I'm not sure you are giving enough information about the complete application to get the best answer. However here are some possible approaches:

  1. Define an isValid() method in your base class, which by default returns true. In your subclasses, you can code specific logic for each Segment or FieldType to return false if any requirements are missing. If you want to report an error message to say which fields are missing, you could add a List argument to the isValid method to allow each type to report the list of missing values.

  2. Use Annotations (as AlexR said above).

The benefit of the above 2 approaches is that meta data is within the code, tied directly to the objects that require it. The disadvantage is that if you want to change the required fields, you will need to update the code and deploy a new build.

If you need something which can be changed on the fly, then Gangus suggestion of Xml is a good start, because your application could reload the Xml definition at run-time and produce different validation results.

Upvotes: 1

AlexR
AlexR

Reputation: 115328

Since java 5 is released this kind of metadata can be stored using annotations. Define your own annotation @MandatoryField and mark all mandatory fields with it. Then you can discover object field-by-field using reflection and check whether not initiated fields are mandatory and throw exception in this case.

Upvotes: 0

Gangnus
Gangnus

Reputation: 24464

I think, the best placement for such data will be normal XML file. And for work with such data the best structure will be also XMLDOM with XPATH. Work with classes will be too complicated.

Upvotes: 0

Related Questions