2
\$\begingroup\$

I'm relatively new to programming and I was trying to work a project.

I would like recommendations of how to annotate or comment my project and any improvement I could make to it, any suggestion is welcome,

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.*;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.ArrayList;

public class Util {

    /*/
    DOC Generation -> XML with ArrayList String elements
     */
    public Document docBuilder(ArrayList<String[]> elements) throws ParserConfigurationException {
        DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();
        Document xmlDoc = xmlBuilder.newDocument();

        Element rootElement = xmlDoc.createElement("root");
        xmlDoc.appendChild(rootElement);

        Element mainElement = xmlDoc.createElement("elements");
        rootElement.appendChild(mainElement);

        boolean headerDefined = false; //First while will be to define header
        String[] header = new String[elements.size()]; //Header initialization

        /*/
        DOC Generation -> XML Generation of every ELEMENT
        */
        for (String[] node : elements) { //FOR every ArrayString
            if (headerDefined) {
                Element nodesElements = xmlDoc.createElement("element");
                mainElement.appendChild(nodesElements);

                for (int j = 0; j < node.length; j++) {
                    node[j] = node[j].replaceAll("\"", "").trim();
                    Element nodesValues = xmlDoc.createElement(header[j]);
                    nodesElements.appendChild(nodesValues);
                    Text nodeTxt = xmlDoc.createTextNode(node[j]);
                    nodesValues.appendChild(nodeTxt);
                }
            }
            /*/
            DOC Generation -> Array Generation of every COL Name for NODES
            */
            else {
                header = node;
                for (int k = 0; k < node.length; k++) {
                    header[k] = header[k].replaceAll("[^a-zA-Z0-9]", "");
                    //We want to make sure NODE isn't NUMERIC. If it is, we make a patch
                    try {
                        Integer.parseInt(header[k]);
                        header[k] = "node" + header[k];
                    } catch (NumberFormatException e) {
                    }
                }
                headerDefined = true;
            }
        }
        return (xmlDoc);
    }

    /*/
    XML Generation -> Transform DOC Data to XML Format
     */
    public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException {
        TransformerFactory xmlTransformerFactory = TransformerFactory.newInstance();
        Transformer xmlTransformer = xmlTransformerFactory.newTransformer();
        xmlTransformer.setOutputProperty(OutputKeys.INDENT, "yes");
        xmlTransformer.setOutputProperty(OutputKeys.METHOD, "xml");
        xmlTransformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        xmlTransformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
        FileOutputStream outputStream = null;
        try {
            outputStream = new FileOutputStream((new File(xmlFile)));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        xmlTransformer.transform(new DOMSource(xmlDoc), new StreamResult(outputStream));
    }

}

https://github.com/codepressed/JAVACSVtoXMLConverter

\$\endgroup\$
1
  • 3
    \$\begingroup\$ This doesn't seem to be a CSV to XML converter. It's just the part of the converter that writes the XML. If you're not going to include more of the program (which might be better), you should retitle. E.g. to Write tabular data to XML. Note that your program doesn't seem that long. You could probably fit the whole thing in the post. A usage example would also be helpful. Either the code that calls these methods with sufficient context that it will run or if you add the rest of the program, show an example command line. \$\endgroup\$ – mdfst13 Nov 17 '20 at 2:46
2
\$\begingroup\$

Line by line analysis

public class Util {

Util is not a good class name. It does not describe what the responsibility or function of the class is. If it did, it would describe the top desktop drawer of code, where all random code snippets are dumped because the authors could not be bothered to think of a proper place. Suffice to say, those kinds of classes don't exist in well maintained code bases. Use something like TabularToXmlConverter instead.

/*/
DOC Generation -> XML with ArrayList String elements
 */

You should have an extremely good reason for creating your own specialized format for documenting your classes and methods. Java platform comes with JavaDoc which is a standardized way of formatting documentation. Programmers know how to read it and expect to see it. When encountered with your style they literally get angry because they have to learn a new (and most likely inferior) format.

DocumentBuilderFactory xmlFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder xmlBuilder = xmlFactory.newDocumentBuilder();

Because your method created the DocumentBuilderFactory, it became responsible for managing it's own dependencies. If you wanted to use the converter to create a bit different kind of XML document, you couldn't do it without changing the class and breaking all code that already uses it. You might want to pass a DocumentBuilder reference to the class and thus employ dependency injection.

Document xmlDoc = xmlBuilder.newDocument();

What is the reason why you build the document in memory? Most often when I have worked with XML, the biggest problem has been memory consumption caused by handling large XML documents that have been loaded into memory. Since you also provided a transformDocToFile it might make more sense to just write the document directly to an OutputStream using the Streaming API for XML (StAX).

boolean headerDefined = false; //First while will be to define header

Do not use end-of-line comments. They are difficult to read, hard to maintain and force you to compress your thoughts into fewer words that make sense. I, for example, have no idea what this comment means. And you should strive to use variable names that describe the purpose of the variable. From the variable name alone I already guessed it's a flag that tells if the header row has been generated. So there isn't any need for a comment here at all. The other end-of-line comments also just tell what the preceding code does adding no additional value. Comments should desribe why something is being done, not repeat what the code already tells. If the code isn't clear, first priority should be making it clearer instead of duplicating it in free verse.

public static void transformDocToFile(Document xmlDoc, String xmlFile) throws TransformerException {

One of your methods is static and the other is not, requiring the caller to create an unnecessary instance of the Util-class.

    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }

You catch one of the possible exceptions and continue happily even though in this particular case you cannot even write to the file.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.