0

I need help with dividing these lines of code and putting them into methods:

   url = new URL(URL_SOURCE);
   con = url.openConnection();
  is = con.getInputStream();
   DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
Document doc = dBuilder.parse(is);
doc.getDocumentElement().normalize();
   NodeList nList = doc.getElementsByTagName("pozycja");

I divied it into:

 public URLConnection openConnectionOfGivenURL(String givenURL) throws IOException {
    URL url = new URL(givenURL);
    return url.openConnection();
}

I dont know what should I do with the rest. Should I name it with getDOM ?

pipilam
  • 587
  • 3
  • 9
  • 22

1 Answers1

1

I think all except first and last line should be in a method. Don't try to divvy that code up further than that. E.g. Document getXml(URL url) or maybe name it downloadXml if you only intend to use it with HTTP(S) urls.

The main reason for not divvying it up further, is that you should use try-with-resources.

Also, you don't need to normalize a parsed DOM, since the parser is already creating a normalized DOM tree.

Document getXml(URL url) {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    URLConnection con = url.openConnection();
    try (InputStream is = con.getInputStream()) {
        return dBuilder.parse(is);
    }
}

Then you use it like this:

URL url = new URL(URL_SOURCE);
Document doc = getXml(url);
NodeList nList = doc.getElementsByTagName("pozycja");
Andreas
  • 154,647
  • 11
  • 152
  • 247