Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting rid of if/else

Tags:

java

In Java, I've to set a POJO class with values. However to decide which setter function to be used, I've to depend on if condition. My current code looks as follow:

// Code written in a function which is called within a loop, while parsing xml file.
if (name.equals("dim1")) {
    line.setDim1Code(Integer.parseInt(value));
} else if (name.equals("dim2")) {
    line.setDim2Code(Integer.parseInt(value));
} else if (name.equals("debitcredit")) {
    line.setDebitOrCredit(value);
} else if (name.equals("basevalue")) {
    line.setBasevalue(Integer.parseInt(value));
} else if (name.equals("rate")) {
    line.setRate(Integer.parseInt(value));
} else if (name.equals("value")) {
    line.setValue(Integer.parseInt(value));
} else if (name.equals("description")) {
    line.setDescription(value);
} else if (name.equals("vatbasetotal")) {
    line.setVatBaseTotal(value);
} else if (name.equals("vattotal")) {
    line.setVatTotal(value);
}

This is just an example but I've 70+ such properties to be set. My code is working but I wonder if it is right way of doing things?

AFAIK, such code is against coding best practices. How can we optimise this code in Java? What is Java best practice to deal with such code?

like image 222
Kapil Sharma Avatar asked Aug 27 '15 13:08

Kapil Sharma


People also ask

Why should not use if-else?

The experts in clean code advise not to use if/else since it's creating an unreadable code. They suggest rather using IF and not to wait till the end of a method without real need.


2 Answers

It is actually something, which should be done automatically based on annotations by some library like Jackson 2.0+ or something similar (I am parsing only JSON so far)

Then the object looks like this :

@XmlAccessorType(XmlAccessType.FIELD)
    public class Employee
    {
        @XmlAttribute
        @XmlID
        protected String id;

        @XmlAttribute
        protected String name;

        @XmlIDREF
        protected Employee manager;

        @XmlElement(name="report")
        @XmlIDREF
        protected List<Employee> reports;

        public Employee() {
            reports = new ArrayList<Employee>();
        }
    }
like image 61
libik Avatar answered Oct 12 '22 16:10

libik


You can try Java Architecture for XML Binding (JAXB), here you have a tutorial. i.e:

    File file = new File("C:\\file.xml");
    JAXBContext jaxbContext = JAXBContext.newInstance(Pojo.class);

    Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
    Pojo pojo= (Pojo) jaxbUnmarshaller.unmarshal(file);
like image 37
Daniel Boncioaga Avatar answered Oct 12 '22 14:10

Daniel Boncioaga