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!
An example of a coding standard is a set of conventions adopted in any common printed work in a language (for example, the C standard for coding, which received the acronym K&R, comes from the classical books of C by Kernighan and Ritchie).
During assignments: Get a good approach or overall design before too much coding. Use code coding habits & style. Write simple lines of code connected by variables. Write small increments of code, and compile & run that.
The Java code conventions are defined by Oracle in the coding conventions document. In short, these conventions ask the user to use camel case when defining classes, methods, or variables. Classes start with a capital letter and should be nouns, like CalendarDialogView .
I'll toss out an alternative:
public static B CreateFromA(A a) { }
This uses a factory syntax, to suggest that you can crank out a B
given an A
, but avoiding anything that looks like a conversion.
I'd either use the constructor method or explicit conversion.
public static explicit operator B(A typ)
{
}
In general, I think this is very subjective. We could all post an answer with the different method and see which one gets voted up the most, but really each way has different benefits and deficiencies. It would depend more on the context and how this pattern is done throughout the rest of the code.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With