Isabella Riquetti
Isabella Riquetti

Reputation: 425

Best way for several classes to share the same attributes in C#

I've already seen some ways to do this attribute sharing, from the most basic (passing attributes per parameter) and interface (which so far was the cleanest way I've found), but would like to know if there are other ways, maybe even better, of doing this, since I am refactoring my main class and would like to avoid having to do this again for a long time.

The problem is the following, I have a mother class that has several children, however according to the need of the company other children were being created and some methods of the children were passed to the mother and today the mother already has 15 attributes and more 60 methods that can be perfectly divided into classes.

My classes are these confused monsters that I'm not proud of, so you should understand why she's crying over refactoring:

public class A
{
    protected Form myForm = new Form();
    protected WebBrowser myBrowser = new WebBrowser();

    protected List<ComplexType1> List1 = new List<ComplexType1>();
    protected List<ComplexType2> List2 = new List<ComplexType2>();
    protected List<ComplexType3> List3 = new List<ComplexType3>();
    protected List<ComplexType4> List4 = new List<ComplexType4>();

    protected ComplexType5 myData;
    //  And more attribute ...

    public A() {    }   
    protected virtual void Method1() {}
    protected virtual void Method2() {}
    protected virtual void Method3() {}
    protected virtual void Method4() {}
    protected virtual void Method5() {} 

    //  And more and more methods ...
}

public class B : A
{
    protected ComplexType6 anotherData;

    public B() : base() {}
    protected override void Method3() {}
    protected override void Method4() {}
    protected virtual void Method6() {}
}

public class C : A
{       
    public C() : base() {}
    protected override void Method1() {}
    protected virtual void Method6() {}
    protected virtual void Method7() {}
}

//  And more and more child classes ...

Upvotes: 0

Views: 768

Answers (1)

Carbine
Carbine

Reputation: 7903

From the looks of it, you have a humungous class which is being inherited by many other class.

The best way to tackle a huge class and coupled with inheritance is to avoid it.

You will have a lot of problems with both the cases, if you have too much functionality it base class you are bound to modify it. Modifying the base class will impact all the derived classes and you it will be difficult to keep track and test it. Coupled with shared variables, you will not know if the base class updated it or the derived class updated it.

I would suggest break down the base class into smaller classes for closely related functionality. Prefer composition over inheritance. This will reduce your member/variable sharing and have a manageable code.

Upvotes: 2

Related Questions