Note: I've read this and its not quite what I'm looking for:
I have an app that builds up XML from an input file and creates one of two outputs, depending upon the file chosen. It was a "quick n dirty" app to get round an immediate problem, but I know it's going to find further use and want to pre-empt this by refactoring.
At the moment I have a "builder" class that takes the input (in its ctor) and exposes a property which is the required XElement. However, many of the XElements are identical, except for the content, for both of my XML outputs. (Oh, please ignore the validation part which I'll refactor separately)
So I'm looking at a sensible way of DRYing my app:
At the moment I have something like this.
public FirstBuilder(string line, int lineNumber, bool output, string subjectType, string inquiryCode)
{
var split = Regex.Split(line, @"\|");
if (split.Count() != SPLIT_COUNT)
throw new Exception("This does not appear to be a valid First Type input file.");
_lineNumber = lineNumber;
_reportId = output ? TXT_REPORT_ID : XML_REPORT_ID;
_subjectType = subjectType;
_responseType = output ? TXT_RESPONSE_TYPE : XML_REPONSE_TYPE;
_inquiryCode = inquiryCode;
_product = split[0];
_number = split[1];
_amount = split[2];
_currency = split[3];
_name = split[4];
_nationalId = split[5];
_gender = split[6];
_dateOfBirth = split[7];
_nationality = split[8];
}
public XElement RequestElement
{
get
{
return new XElement("REQUEST",
new XAttribute("REQUEST_ID", _lineNumber),
RequestParametersElement,
SearchParametersElement);
}
}
private XElement RequestParametersElement
{
get
{
return new XElement("REQUEST_PARAMETERS",
ReportParametersElement,
InquiryPurposeElement,
ApplicationElement);
}
}
private XElement ReportParametersElement
{
get
{
return new XElement("REPORT_PARAMETERS",
new XAttribute("REPORT_ID", _reportId),
new XAttribute("SUBJECT_TYPE", _subjectType),
new XAttribute("RESPONSE_TYPE", _responseType));
}
}
etc. etc...
//used by
var x = new FirstBuilder(x,y,z,etc.).RequestElement();
This all works and is very fast...but SecondBuilder
also uses these same elements, along with some different ones.
So I'm looking at the "best" way to refactor these out: Shared Abstract class with inheritance? Shared "Helper" classes? Extension methods to return "built" elements? Classes per element that extend XElement?
My suspicion is that this will balloon from the two examples as a quick solution to around 30 in then next month!
THX.
I would refactor the private properties to methods that receive the required values as input parameters. You can then move them into a PartsBuilder
class and use that one in you concrete builders.