I created simple export tool for my project. My requirments was to create one csv file for details of my hero which contains name, level, gold etc. And second file for list of items. Both of files contains static header and generated Data.
First, let me share my model classes:
public class Hero {
private String name;
private int level;
private List<Item> items = new ArrayList();
private String className;
private BigDecimal gold;
//getters setters constructors
}
public class Item {
private int id;
private String name;
private double weight;
//getters setters constructors
}
public class Weapon extends Item {
private int dmg;
private int level;
//getters setters constructors
}
public class Food extends Item {
private int capacity;
private int hpRegen;
//getters setters constructors
}
I wont share real classes, because they are a little too big, so I have prepared sample classes.
And here we go with example 'exporter'. This class has two public methods which return CSVWriter
which we can use to save data to file.
public class HeroWriter {
private Hero hero;
private final static String[] HERO_INFO_HEADER = {
"server",
"date",
"name",
"class",
"level",
"gold"
};
private final static String[] ITEM_LIST_HEADER = {
"id",
"name",
"weight",
"dmg",
"hp",
"required level",
"capacity"
};
public HeroWriter(Hero hero) {
this.hero = hero;
}
public CSVWriter writeHeroInformation() {
CSVWriter writer = new CSVWriter(null);
writer.writeNext(HERO_INFO_HEADER);
String[] heroInformation = {
"Mocked Server",
new Date().toString(),
hero.getName(),
hero.getClassName(),
hero.getLevel()+"",
hero.getGold().toString()
};
writer.writeNext(heroInformation);
return writer;
}
public CSVWriter writeItemList() {
CSVWriter writer = new CSVWriter(null);
writer.writeNext(ITEM_LIST_HEADER);
for (Item item : hero.getItems()) {
if(item instanceof Weapon) {
Weapon weapon = (Weapon) item;
String[] weaponDetail = {
weapon.getId() + "",
weapon.getName(),
weapon.getWeight() + "",
weapon.getDmg() + "",
"-",
weapon.getLevel() + "",
"-"
};
writer.writeNext(weaponDetail);
} else if (item instanceof Food) {
Food food = (Food) item;
String[] foodDetail = {
food.getId() + "",
food.getName(),
food.getWeight() + "",
"-",
food.getHpRegen() + "",
"-",
food.getCapacity() + ""
};
writer.writeNext(foodDetail);
}
}
return writer;
}
}
I would like to as you to review HeroWriter class, because I have problem with OOP and would like to improve in this aspect.
I was thinking that maybe I could create Exportable
interface which contains method like String[] export();
and I would implement it in Hero/Weapon/Item class that would help me remove instanceof part of code. But I am not sure if it is good idea.
toString
method in your classes ? \$\endgroup\$