0

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.

1 Answer 1

1

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()
    { ... }
    ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

If i want return attribute by requested type, how i should implement method? public Attribute<T> GetAttribute(T){ // what should be there? }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.