I have some repeated pieces of code. This contradicts with DRY principe. But i don't know how replace this with generic method.
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();
}
...
}
I like to replace duplicate methods, like ClearRelatedToFirst()
and ClearRelatedToSecond()
, to ClearRelatedToAttrib<TYPE>()
. And inside that generick method i don't know how to choose which bool
-variable i need to set or which hashset
i need to clear. Same to other duplicate methods. Can you show me, how i can refactor this code? Thanks.
See code below:
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()
{ ... }
...
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.