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?
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.
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>();
}
}
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With