I have this Java app that I’m doing some web scraping with using the JSoup library. I’m using the library and it’s returning a collection of Strings 6 of them. I need to map these 6 random strings to properties on an object. I know which order the strings are coming in and what number maps to what property. I don’t feel like my approach is the best way to handle this. It feels lose, readability sucks, and I’m just wondering if there’s a better way to do this. I was thinking using enum’s or something alone those lines. Long story short here’s a code snippet. Thanks for any help.
List<String> strings = JSoup.getStrings();
Car car = new Car();
int i = 0;
for(String s : strings) {
switch (i) {
case 0:
car.setMake(s);
break;
case 1:
car.setModel(s);
break;
.....
}
i++;
}
Since this question is about best practices, you should consider providing a constructor in Car that takes a List of Strings as an input. The constructor will then initialize the fields for the car from the List of Strings one by one because that’s what constructors are for any way. This means that the code for populating your car instance will now be in a single place, i.e inside the Car class.
This approach will eliminate the need for the code that creates a Car instance to manually initialize the Car instance. No matter how many different classes create a Car, the initialization code will not be duplicated in each of these classes. Placing the initialization code inside car itself promotes reusability. Isn’t that what classes are written for?