Java Reference
In-Depth Information
The persistDVD method has a private StringBuilder variable that we will use to create a
representation of a complete record. Prior to JDK 5, we might have used a StringBuffer to
build this; however, the StringBuffer is internally synchronized to make it thread safe. Since
the variable we will be using is a method variable, not a class variable, we do not need the syn-
chronization. The StringBuilder class will therefore provide us with better performance.
Since each record is a fixed length, it is easy to start with a blank record of the correct
length, then replace the blanks with the field data. We have a static empty field that was
declared in line 66 and initialized in lines 77-79 as described earlier in the chapter. This
makes it easy for us to create a StringBuilder of the correct length and contents in line 360:
360 final StringBuilder out = new StringBuilder(emptyRecordString);
Having created our variable, we will use StringBuilder 's replace method to put the field
data in the correct locations within the record field. By making a utility inner class we can save
replicating the code:
362 class RecordFieldWriter {
363 int currentPosition = 0;
364 void write(String data, int length) {
365 out.replace(currentPosition,
366 currentPosition + data.length(),
367 data);
368 currentPosition += length;
369 }
370 }
371 RecordFieldWriter writeRecord = new RecordFieldWriter();
We can then use our utility inner class to convert the DVD record to the StringBuilder
equivalent:
373 writeRecord.write(dvd.getUPC(), DVD.UPC_LENGTH);
374 writeRecord.write(dvd.getName(), DVD.NAME_LENGTH);
375 writeRecord.write(dvd.getComposer(), DVD.COMPOSER_LENGTH);
376 writeRecord.write(dvd.getDirector(), DVD.DIRECTOR_LENGTH);
377 writeRecord.write(dvd.getLeadActor(), DVD.LEAD_ACTOR_LENGTH);
378 writeRecord.write(dvd.getSupportingActor(),
379 DVD.SUPPORTING_ACTOR_LENGTH);
380 writeRecord.write(dvd.getYear(), DVD.YEAR_LENGTH);
381 writeRecord.write("" + dvd.getCopy(), DVD.COPIES_LENGTH);
â– 
Caution When working on your Sun assignment you must make the design decisions that make sense
to you and that you are willing to defend when you go to do the exam portion of the certification. This can
(and in some cases should) mean that you may make design decisions that contradict our design decisions—
we are, after all, working on different assignments with different requirements. Do not be afraid to consider
other options. A good place to discuss one of our design decisions or one of your design decisions is
JavaRanch ( http://www.javaranch.com ).
Search WWH ::




Custom Search