【发布时间】:2012-02-05 20:05:38
【问题描述】:
注意:我已阅读 this,但它并不完全符合我的要求:
我有一个应用程序,它从输入文件构建 XML 并根据选择的文件创建两个输出之一。这是一个解决直接问题的“快速和肮脏”的应用程序,但我知道它会找到进一步的用途,并希望通过重构来抢占先机。
目前我有一个“构建器”类,它接受输入(在其 ctor 中)并公开一个所需的 XElement 属性。但是,对于我的两个 XML 输出,除了内容之外,许多 XElement 都是相同的。 (哦,请忽略验证部分,我将单独重构)
所以我正在寻找一种明智的方式来干燥我的应用程序:
目前我有这样的东西。
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();
这一切都有效并且速度非常快......但SecondBuilder 也使用这些相同的元素,以及一些不同的元素。
所以我正在寻找重构这些的“最佳”方法: 具有继承的共享抽象类? 共享“助手”课程? 返回“内置”元素的扩展方法? 扩展 XElement 的每个元素的类?
我怀疑这将从两个示例中迅速增长到下个月大约 30 个的快速解决方案!
谢谢。
【问题讨论】:
标签: c# refactoring xelement