I'm re-writing some code, and I've decided the way to recreate the class, as there are a fixed number of sheets, I'm creating them as enums. This is a decision based on the readability of a builder patter vs a telescoping constructor.
The code I'm grabs some some .xls files, adds headers (and reads some from other .xls files) and perhaps some sub-sheets. It then merges a variety of these sheets together in a specific way to make tabs on a main excel workbook. My issue is that some of the workbook tabs take different numbers of sheets are arguments. I'm trying to apply the builder pattern. This is the sort of code I'm trying to write:
public enum workBookSheet {
mySheet1("Name1","mainSheet1.xls",true,1).addSubSheet("pathToSubSheet1.xls"),
mySheet2("Name2","mainSheet2.xls",true,2).addHeaderSheet("pathToHeaders.xls").addSubsheet("pathtoSubSheet2.xls");
private String tabName;
private String mainSheetName;
private Boolean available;
private Integer order;
private String subSheetName;
private String headerSheetName;
private workBookSheet(String tabName, String mainSheetName, Boolean available, Integer order){
this.tabName = tabName;
this.mainSheetName = mainSheetName;
this.available = available;
this.order = order;
}
public workBookSheet addSubSheet(String subSheetName){
this.subSheetName = subSheetName;
return this;
}
public workBookSheet addHeaderSheet(String headerSheetName){
this.headerSheetName = headerSheetName;
return this;
}
}
The error that java is giving me seems to be saying that Java expects my enum declaration (comma delimited list of 'enum constructors' at the top) to only have the constructor in it, and not additional methods. I can move those methods to a 'builder' method below, without complaint.
public void buildSheets(){
mySheet1.addSubSheet("pathToSubSheet1.xls");
mySheet2.addHeaderSheet("pathToHeaders.xls").addSubSheet("pathtoSubSheet2.xls");
}
Is this the only way to implement a builder pattern on an enum? It does require me to run a separate method, which isn't too much hassle. IT does feel like I'm breaking the pattern though (I guess, not such a bad thing if this works.)
N.B I've had a good look around to see if anyone else has asked this question, on SO or elsewhere on the web. The closest I found was a question here on Enums and Factories, but that doesn't quite answer my question. Also I'm aware this isn't quite the builder pattern, as I don't have a separate class that then accepts a build() method that creates a new enum. I guess this is the root of the problem in my initial design, but I am relatively new to Java.
So Is there a better way to use a builder pattern on a Java enum? Or is what I have 'close enough'?