C# Don';Don’不要重复你自己或者通过重复你自己变得更清楚?
我有下面这个基类:C# Don';Don’不要重复你自己或者通过重复你自己变得更清楚?,c#,dry,code-duplication,C#,Dry,Code Duplication,我有下面这个基类: abstract class RequiredString { protected readonly string _text; public RequiredString(string name, string text) { if (string.IsNullOrWhiteSpace(text)) throw new TextEmptyException($"The '{name}' field is r
abstract class RequiredString {
protected readonly string _text;
public RequiredString(string name, string text)
{
if (string.IsNullOrWhiteSpace(text))
throw new TextEmptyException($"The '{name}' field is required");
_text = text;
}
public RequiredString(string name, string text, int maxLength): this(name, text)
{
if (_text.Length > maxLength)
throw new TextLengthTooLongException($"The '{name}' field length is too long ({text.Length}/{maxLength})");
}
public static implicit operator string(RequiredString field)
{
return field._text;
}
}
我有十几个从基类继承的类。它们都有一个最大长度:
例如:
public sealed class Email : RequiredString
{
private const int Length = 255;
private const string Name = "Email";
public Email(string text) : base(Name, text, Length)
{
try
{
new MailAddress(_text);
}
catch (FormatException ex)
{
throw new EmailFormatException($"'{_text}' field is not a valid email string", ex);
}
}
public static implicit operator Email(string text)
{
return new Email(text);
}
}
假设读者检查了Email类,但没有看到基类
他/她是否清楚长度检查发生在基类中?
它有意义吗?还是应该在每个继承的类中进行长度检查?
您将如何重构代码以使其更干净
谢谢大家! 在继承的类中有
Length
字段,但在基类中检查它会令人困惑。如果我在继承类中看到它,我希望它被检查。“代码>最大长度定义在哪里?考虑制作<代码>长度>代码>基类中的抽象只读属性。<代码>对他/她是否清楚,长度检查发生在基类中?< /代码>是足够的,如果它被传递到基类。您调用基本构造函数。所以读者应该检查基类的代码。这是自然的,没什么问题。不看基本构造函数与忽略部分代码是一样的:读者是唯一的一个……而当你考虑MJWILS的建议时,也要考虑将它从代码> >长度>代码>改为<代码>最大长度。在继承的类中有<代码>长度字段,但是在基类中检查它是混淆的。如果我在继承类中看到它,我希望它被检查。“代码>最大长度定义在哪里?考虑制作<代码>长度>代码>基类中的抽象只读属性。<代码>对他/她是否清楚,长度检查发生在基类中?< /代码>是足够的,如果它被传递到基类。您调用基本构造函数。所以读者应该检查基类的代码。这是自然的,没什么问题。不看基本构造函数与忽略部分代码是一样的:读者是唯一的责任者。当您考虑MjWess的建议时,也应考虑将其从代码>长度>代码>重命名为<代码>最大长度。