I have two classes, A and B. B knows about A, and A doesn’t know about B. B has properties that can be nicely set from A, although there is no inheritance shared between A and B. There will be many times when I need to assign a B’s properties from an A, but I’m looking for pointers on where I should put that code.
public class A
{
}
public class B
{
//constructor?
public B(A a)
{
//set b's properties from a
}
//factory method?
public static B FromA(A a)
{
B b = new B();
//set b's properties from a
return b;
}
//setter method?
public static void SetBFromA(B b, A a)
{
//set b's properties from a
}
//assignment method?
public void AssignFrom(A a)
{
//set b's properties from a
}
}
//static helper class?
public static class BHelper
{
public static B GetBFromA(A a)
{
B b = new B();
//set b's properties from a
return b;
}
public static void SetBFromA(B b, A a)
{
//set b's properties from a
}
}
Which, if any, of these are common practice? Do any of them carry implications based on their signature? For example, would using the constructor usually convey that the B is holding a reference to the A passed in? These are the kinds of considerations I’m thinking about.
Thanks!
All of the options you mention are valid. Which you would choose would depend on the particular circumstances.
The constructor pattern would be the choice when B cannot exist without the data from A.
The factory method would be the pattern of choice when the values B gets are dependant on values in A or B. Especially if B has descendants that a value in A would provide a choice of construction.
The setter method would not be applicable in your scenario as this would be used when A and B do not know of each other and a third party needs to intercede.
This is essentially a visitor pattern. A visits B and leaves something of itself (thinks of bachelor days). This would be the pattern of choice if the data from A is optional for B.