Initializing 2 objects that require each other as parameters

I have the code following the template:

class A
{
    private B _b;

    public A(B b)
    {
        _b = b;
    }
}

class B
{
    private A _a;

    public B(A a)
    {
        _a = a;
    }
}

      

Is this considered bad design?
What's the easiest way to initialize both classes, besides adding a method like void SetA(A a)

in B?

+3


source to share


1 answer


Is this bad design?

Who knows (it depends on your actual use ...), but if your code is similar to your code snippet, you might be trying to use composition over inheritance when inheritance would work better.

Consider the following suggestions:

  • The wolf has an animal (really?).
  • The car has an engine (really!);
  • The office chair has a chair (really?).
  • ... etc.

Actually, I doubt it B

might have A

, but I'm sure it B

might A

.

On the other hand, if you used class IDs A

or B

to show us a sample code, but in your code your classes cannot be expressed using the is verb (for example, B

is A

), then your design is probably correct.



BTW, if A

u B

are 1: 1 , where one A

has B

and one B

has A

, if the association makes sense, this is not bad design per se ... For example, an object User

has UserProfile

, but UserProfile

has an owner User

:

public class User 
{
     public UserProfile Profile { get; set; }
}

public class UserProfile
{
     public User OwnerUser { get; set; }
}

      

What's the easiest way to initialize both classes, besides adding a method such as void SetA (A a) to B?

The easiest way is to use read and write properties (i.e. properties with getter and setter) and set them as soon as their class has already been created, or use constructors. There is really no simplest way, but there is the most appropriate way depending on your actual use .

Summary

Use inheritance when you can express a class relationship using the is verb (i.e. Cat

is Animal

), while you are using composition when you can express a so-called relationship using has verb (i.e. a House

has TV

).

+3


source







All Articles