I have a situation where I need to classify a bunch of files according to several parameters (file name, content, specific features of the content if it is one type of file, other features if it is another) and after identifying the right type of file, I'll create an object passing that file to a constructor. This part is computationally expensive, and i already have it working adequately.
The thing is, the constructor of each object will basically do the same processing that the classifier did, because most of the things the classifier checks for will be repeated when I'm creating the object. But this leads to an awful lot of code duplication and processing duplication. All the objects I'm creating have inherit from the same base class.
Is there a cleaner way to achieve this and avoid the duplication (ie some standard design pattern)?
I have thought about simply throwing the files at all the different possible object constructors and bail out of the constructors with exceptions if it's not the right file for that constructor, but i don't specially enjoy using exceptions for code branching and flow (i don't have anything specific against it, i just think it has an unpleasant smell). Another thing I've thought about was moving the processing part out of the object constructors and use the values i got from the classifier to populate the object after creating it "empty", but that way I'd be moving behavior out of the class, and that doesn't feel right either, even if it does work.
Here is an example of what I'm trying to achieve:
file A.abc
file B.abc
(potentially hundreds of files on each run)
Classifier.Scan(file A.abc)
<heavy lifting operations>
<decides file A is of type alpha>
var a= new alpha(file A.abc)
<now constructor of alpha will do most of the same heavy lifting operations again to create the object>
Classifier.Scan(file B.abc)
<heavy lifting operations>
<decides file B is of type beta>
var b= new beta(file B.abc)
<now constructor of beta will do most of the same heavy lifting operations again to create the object>
so on for other files.
I'm coding it in c#, but i don't think the problem nor the solution are language specific. Thank you very much for your time.
Aucun commentaire:
Enregistrer un commentaire