I have written code responsible for saving data to a file using Serialization
. I think that a natural way to avoid repetition is to use inheritance but I'm not sure if it would work because of generics.
How can I remove all the repetition in the below code?
Some general information:
There is a class StoredItem and classes PipeCable, Element, ValveMotor which extend StoredItem.
There is Data class in which are ObservableLists of PipeCable, Element, ValveMotor
The code that I'd like to improve but I don't know how:
private void savePipeCableList(Data data) {
try {
Path path = Paths.get(Strings.dataPipeCableFileName);
OutputStream fos = Files.newOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new ArrayList<PipeCable>(data.getPipeCableList()));
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveElementList(Data data) {
try {
Path path = Paths.get(Strings.dataElementFileName);
OutputStream fos = Files.newOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new ArrayList<Element>(data.getElementList()));
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void saveValveMotorList(Data data) {
try {
Path path = Paths.get(Strings.dataValveMotorFileName);
OutputStream fos = Files.newOutputStream(path);
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(new ArrayList<ValveMotor>(data.getValveMotorList()));
oos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I will appreciate any suggestions.