Reading contacts from an XML file

The next improvement we'll make is to have the address book viewer application read an XML file to get contact information instead of a hard-coded list. There are a couple of nuances with this integration, so let's try that out now!

The list of contacts being displayed by the address book viewer is from hard-coded data in the ContactUtil class. Here's the sample structure of the XML file we'd like to read it from:

    <?xml version="1.0"?> 
    <addressbook> 
      <contact> 
        <firstname>Edsger</firstname> 
        <lastname>Dijkstra</lastname> 
        <address> 
          <street>5612</street> 
          <city>AZ</city> 
          <state>Eindhoven</state> 
          <country>Netherlands</country> 
        </address> 
        <phone>345-678-9012</phone> 
      </contact> 
      <contact> 
          ... 
      </contact> 
      ... 
    </addressbook> 

The root node is addressbook and within it are several contact child nodes. Each contact node has firstname, lastname, and a nested address node, as shown.

In order to have the application read from an XML file, what we'd like to do is the following:

  1. Remove the existing hardcoded logic from the module
    packt.addressbook.
  2. Implement functionality of opening and reading the XML file in a separate module. This module will contain code to read from the source XML file and return a list of contacts.
  3. Update the main address book module to depend on this new module to get the list of contacts.

The fact that we need to do #1 is obvious. But why #2 and #3? Why move that portion of the code to its own module? Well, as you can imagine, there's no right answer for this one.

The goal of modularization is to achieve the separation of monolithic code into modular building blocks that can be freely reused and replaced. Consider the scenario where, in the future, you decide to not use an XML file to store the data, but instead, read from a JSON file. Or a database. Or even a REST API! No matter what the new source is, the fact that there is this one separate module that acts as a provider of the list of contacts makes the change relatively easy. All you have to do then is to remove the XML-based module we'll create now and plug in a new module that reads from the new source of data. Granted, you'll still need to change the consumers to depend on the new module. But the change will be minimized, and so will the scope of any side effects.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.16.135.225