我有一些重复的代码。这与DRY原则相矛盾。但我不知道如何用通用方法取而代之。
class Foo
{
public bool isFirstAttribHasRightValue;
public bool isSecondAttribHasRightValue;
private readonly T1 _firstAttrib;
private readonly T2 _secondAttrib;
public HashSet<T1> relatedToFirstAttrib;
public HashSet<T2> relatedToSecondAttrib;
...
public C()
{ ... }
public T1 GetFirstAttrib(T3 somevalue)
{
return (somevalue != othervalue) || isFirstAttribHasRightValue ? _firstAttrib : default(T1);
}
public T2 GetSecondAttrib(T3 somevalue)
{
return (somevalue != othervalue) || isSecondAttribHasRightValue ? _secondAttrib : default(T2);
}
public ClearRelatedToFirst()
{
isFirstAttribHasRightValue = true;
relatedToFirstAttrib.Clear();
}
public ClearRelatedToSecond()
{
isSecondAttribHasRightValue = true;
relatedToSecondAttrib.Clear();
}
...
}
我想将重复的方法(例如ClearRelatedToFirst()
和ClearRelatedToSecond()
)替换为ClearRelatedToAttrib<TYPE>()
。在那个generick方法中,我不知道如何选择我需要设置的bool
- 变量或我需要清除哪个hashset
。
与其他重复方法相同。你能告诉我,我怎么能重构这段代码?
感谢。
答案 0 :(得分:1)
见下面的代码:
class Attribute<T>
{
public bool isRightValue;
public HashSet<T> relatedHashSet;
private T _value;
public T GetValue(T3 somevalue)
{
return (somevalue != othervalue) || isRightValue ? _value : default(T);
}
public Clear()
{
isRightValue = true;
relatedHashSet.Clear();
}
}
class Foo
{
public Attribute<T1> firstAttribute;
public Attribute<T2> secondAttribute;
...
public Foo()
{ ... }
...
}