jeudi 14 janvier 2016

Design pattern for reading from a stream and populating an object

I have a class with many member fields. This class is populated from a structured file.
For performance I use streaming-sax approach to populate the class.
The code is similar to the following:

if(currentToken.equans("company_name")) {  
   this.companyName = reader.nextString();    
}  
else if(currentToken.equals("managers")) {  
   this.managers = (ArrayList<Manager>)parseManagers(reader);  
}  
else if(currentToken.equals("contractors")) {  
   this.contractors = (ArrayList<Contractor>) parseContractors(reader);  
}   
else if(currentToken.equals("revenew")) {  
   this.revenew = Double.parseDouble(currentToken.nextString());  
}  
etc  

You get the idea.
The code works but it is a very long list of if/else statements which makes it hard to hard to read and maintain (in the long run).
How can I improve this having the following in mind:
1) I want to keep the fact that I can populate each member field according to each type. I don't want to use some kind of reflection to make the code generic.
2) In some cases I just assign the next value from the string e.g. for primitives but in others I need to parse the actual value to get the list (which is more or less the same code as the one posted for different token names)
3) I am interested in performance. I don't want to create "tons" of small classes if they affect performance just to remove the big if/else code.

Aucun commentaire:

Enregistrer un commentaire