Kapil Sharma
Kapil Sharma

Reputation: 10427

Getting rid of if/else

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?

Upvotes: 5

Views: 573

Answers (4)

Rainbolt
Rainbolt

Reputation: 3660

Rather than having a separate field and setter for each property, create a dictionary to hold all of your properties. Borrowing code from How do you create a dictionary?:

private Map<String, String> properties;

// Constructor
public MyClass() {
    properties = new HashMap<String, String>();
}

// Setter
public string setProperty(String name, String value) {
    properties.put(name, value);
}

// Getter
public string getProperty(String name) {
    return properties.get(name); // May return null. You may want to handle that.
}

Now all 70+ of your properties have only one getter and setter. No giant if-else or switch block.

With a dictionary, you lose some of the contracts that properties provide. For example, I could add a property to the dictionary that shouldn't exist. You can enforce these restrictions yourself (for example, by creating a list of allowed property names and refusing to set any property that is not in the list).

Upvotes: 0

libik
libik

Reputation: 23049

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>();
        }
    }

Upvotes: 5

Sh4d0wsPlyr
Sh4d0wsPlyr

Reputation: 968

What you are probably looking to do is write a dynamic Getter/Setter. A quick Google search will give you a large number of options and approaches, but here is a couple I found quickly.

How to define dynamic setter and getter using reflection?

Invoking setter method using java reflection

I personally like the look of BeanUtils. Simple and easy to understand.

Upvotes: 0

Daniel Boncioaga
Daniel Boncioaga

Reputation: 348

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);

Upvotes: 1

Related Questions